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

异步任务执行顺序

异步任务执行顺序

console.log(1);async function foo() {console.log(2);await bar(); // 关键点:await 会暂停 foo 的执行console.log(3); // 被放入微任务队列(在 bar 的 Promise 解决后)
}async function bar() {console.log(4);await Promise.resolve(); // 暂停 bar 的执行console.log(5); // 被放入微任务队列
}setTimeout(() => console.log(6), 0); // 宏任务foo();new Promise(resolve => {console.log(7);resolve();
}).then(() => console.log(8)); // 微任务console.log(9);

执行步骤详解:

  1. 同步代码执行

    • console.log(1) → 输出 1
    • 调用 foo()
      • console.log(2) → 输出 2
      • 调用 bar()
        • console.log(4) → 输出 4
        • await Promise.resolve() 暂停 bar,将 console.log(5) 放入微任务队列
      • await bar() 暂停 foo,将 console.log(3) 标记为等待(但尚未入队)
    • new Promise 同步执行:
      • console.log(7) → 输出 7
      • resolve() → 将 console.log(8) 放入微任务队列
    • console.log(9) → 输出 9
    • 当前输出:1, 2, 4, 7, 9
  2. 微任务队列处理

    • 微任务队列初始内容:[输出5, 输出8]
    • 执行第一个微任务:console.log(5) → 输出 5
      • 关键:此时 bar() 的 Promise 解决,触发 foo() 的等待结束
      • foo() 中的 console.log(3) 被放入微任务队列
    • 执行第二个微任务:console.log(8) → 输出 8
    • 执行第三个微任务:console.log(3) → 输出 3
    • 输出:5, 8, 3
  3. 宏任务队列处理

    • 执行 setTimeout 回调:console.log(6) → 输出 6

最终输出顺序:

1 → 2 → 4 → 7 → 9 → 5 → 8 → 3 → 6

关键机制说明:

  1. await 的双重暂停

    • await bar() 暂停 foo 时,console.log(3) 不会立即入队
    • 必须等待 bar() 的 Promise 解决(即 console.log(5) 执行后),console.log(3) 才加入微任务队列
  2. 微任务执行顺序

    微任务队列初始化
    微任务队列初始化
    触发foo继续
    同步代码
    输出5
    输出8
    输出3
  3. 优先级规则

    • 同步代码 > 已存在的微任务 > 新生成的微任务 > 宏任务
    • 微任务队列按 先进先出 (FIFO) 顺序执行

常见误区:

  • 误认为 await 后的代码会立即入队(实际需等待右侧 Promise 解决)
  • 忽略链式微任务的动态生成(如 console.log(3)console.log(5) 执行后才入队)
  • 混淆微任务和宏任务的优先级(微任务总是优先于宏任务)

你的理解完全正确!这个顺序展示了 JavaScript 事件循环的精细调度机制。

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

相关文章:

  • DC6v-36V转3.2V1A恒流驱动芯片WT7017
  • 【嵌入式C语言】五
  • 如何一个响指删除计算机里的一半文件?(二)
  • 【工具】多图裁剪批量处理工具
  • 基于element-plus和IndexedDB数据库的基础表单
  • 嵌入式:Linux软件编程:线程
  • 深入浅出的 RocketMQ-面试题解析
  • AI架构师生存手册:图解避坑MCP工具链/智能体RAG/推理蒸馏实战
  • TF 上架协作实战,跨部门配合下的内测发布节奏管理
  • Cursor CLI 技术解析:免费调用 GPT-5 的命令行方案
  • 工控机的用途与介绍:工业自动化的重要引擎
  • [激光原理与应用-287]:理论 - 波动光学 - 电磁波既能承载能量,又能承载信息?
  • Systemd Service 文件详解
  • 反射和类加载机制
  • Leetcode 最小生成树系列(2)
  • 深入解析 Monkey OCR:本地化、多语言文本识别的利器与实践指南
  • 德州扑克游戏术语
  • 什么是Redis的哨兵模式
  • 针对前面2篇文章的一个细节的修订(UAC ADC/DAC录音播放,以及UAC ADC/PWM录音播放)
  • const修饰指针用法详解
  • libdrm 和 libgbm
  • 零基础从头教学Linux(Day 13)
  • 13_集合框架
  • ScanNet项目介绍
  • Linux网络配置:聚合链路与网桥实战
  • 开疆智能ModbusTCP转Ethernet网关连接FBOX串口服务器配置案例
  • MySQL多表查询案例
  • 360 集团20周年会:战略升级ALL IN Agent,抢占智能体时代先机
  • OSCP - Proving Grounds - CVE-2024-25180
  • 基于WSL搭建Ubuntu 22.04.x LTS开发环境