当前位置: 首页 > news >正文

前端面试:promise...then与asnyc ...await

JavaScript是单线程,没有异步编程的概念,浏览器 / Node 提供了 异步 API(比如定时器、网络请求) 。为了让代码 “不阻塞”,早期用 回调函数 处理异步结果,我们可以通过函数回调机制来实现异步编程。

promise...then...链式调用避免层层嵌套。async...await是Promise 的语法糖,让异步代码更简洁、读起来更像同步,本质还是依赖 Promise。

实际开发中,建议优先用 async/await(简洁)。

  <script>function one() {console.log('回到宿舍先开空调')}function two() {console.log('打卡欧阳春晓锻炼20分钟')}function three() {console.log('洗澡睡觉')}const P1 = new Promise((resolve, reject) => {resolve('回到宿舍')})P1.then(result1 => {console.log(result1)}).then(() => {one();}).then(() => {two();}).then(()=>{three();}).catch(()=>{console.log('先回自习室拿手机'')})
</script>
<script>function one() {console.log('回到宿舍先开空调')}function two() {console.log('打卡欧阳春晓锻炼20分钟')}function three() {console.log('洗澡睡觉')}const P1 = new Promise((resolve, reject) => {resolve('回到宿舍')})async function HH() {try {const result = await P1;console.log(result)one();two();three();} catch (error) {console.log('先回自习室拿手机'')}}HH();</script>
 <script>const P1 = new Promise((resolve, reject) => {resolve('回到宿舍')})const P2 = new Promise((resolve, reject) => {resolve('回到宿舍先开空调')})const P3 = new Promise((resolve, reject) => {resolve('打卡欧阳春晓锻炼20分钟')})const P4 = new Promise((resolve, reject) => {resolve('洗澡睡觉')})async function HH() {try {const [result1,result2,result3,result4] = await Promise.all([P1,P2,P3,P4]);console.log(result1,result2,result3,result4);} catch (error) {console.log('先回自习室拿手机')}}HH();</script>

http://www.dtcms.com/a/326282.html

相关文章:

  • 华为Atlas 200 DK 板卡使用技巧记录(一)修改板卡IP
  • Pytest项目_day12(yield、fixture的优先顺序)
  • CobaltStrike钓鱼鱼饵制作的方式(chm、doc、execl、exe、powshell 上线cs)
  • [特殊字符] OpenCV图像预处理与ResNet-50深度学习分类实战
  • 元数据管理与数据治理平台:Apache Atlas 关系搜索 Relationship Search
  • AI产品经理手册(Ch12-16)AI Product Manager‘s Handbook学习笔记
  • 使用纯NumPy实现回归任务:深入理解机器学习本质
  • C++安装使用eigen库时出现warning C4819问题的解决方案
  • 【网络运维】Linux:LNMP 项目实践
  • NodeJs》》url地址参数 解析 URLSearchParams querystring
  • vscode的wsl环境,怎么打开linux盘的工程?
  • CSS彩虹七色十六进制值
  • langmem
  • 排序与查找,简略版
  • 《算法导论》第 18 章 - B 树
  • linux 秒 安装谷歌浏览器 区分ubuntu和centos 给python爬取网站使用
  • Haystack:面向大模型应用的模块化检索增强生成(RAG)框架
  • 简单Modules 的配置与管理,灵活应对多版本软件环境的需求。
  • 基于SpringBoot+Uniapp的血压监控小程序(Echarts图形化分析)
  • C++进阶:C++11(2)
  • 应用层模拟面试题
  • 【Jmeter】两个函数拼接
  • IPCP(IP Control Protocol,IP控制协议)
  • 李宏毅2025《机器学习》-第十讲:AI“思想钢印”:深入解析大模型的知识编辑技术
  • docter的使用、vscode(cursor)和docker的连接,详细分析说明
  • (一)vscode搭建espidf环境
  • react路由跳转与路由懒加载等(对照vue来说一说不同之处)
  • 前端开发:React(3)—— 组件运作和事件处理
  • 【论文阅读】BEVFormer论文解析及Temporal Self-Attention、Spatial Cross-Attention注意力机制详解及代码示例
  • 如何平衡短期与长期需求