高级前端js【Q389】以下输出顺序多少 (setTimeout 与 promise 顺序)

以下输出顺序多少 (setTimeout 与 promise 顺序)

更多描述

setTimeout(() => console.log(0));
new Promise((resolve) => {
  console.log(1);
  resolve(2);
  console.log(3);
}).then((o) => console.log(o));
 
new Promise((resolve) => {
  console.log(4);
  resolve(5);
})
  .then((o) => console.log(o))
  .then(() => console.log(6));

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 396

1 => 3 => 4 => 2 => 5 => 6 => 0

Author 回答者: xiaochena

以下输出顺序多少 (setTimeout 与 promise 顺序)

setTimeout(() => console.log(0));
new Promise((resolve) => {
  console.log(1);
  resolve(2);
  console.log(3);
})
  .then((o) => console.log(o))
  .then(() => console.log(7));
 
new Promise((resolve) => {
  console.log(4);
  resolve(5);
})
  .then((o) => console.log(o))
  .then(() => console.log(6));
  • 第一次循环
    • 宏任务队列:JavaScript 代码。打印 console.log(1);console.log(3)console.log(4);
    • 微任务队列:[ then((o) => console.log(o)) | [resolve(2)]then((o) => console.log(o)) | [resolve(5)] ]
    • 延时队列:setTimeout(() => console.log(0));
    • 执行微任务队列:then((o) => console.log(o)) | [resolve(2)]then((o) => console.log(o)) | [resolve(5)] 、其中 then((o) => console.log(o)) | [resolve(5)] 执行完成后又向当前微任务队列中加入一个任务 then(() => console.log(6));
    • 执行微任务队列:[ then((o) => console.log(o)) | [resolve(2)]then((o) => console.log(o)) | [resolve(5)] ]。其中 这两个任务又分别陆续返回2个微任务、因此当前微任务队列的执行顺序是 1、[ then((o) => console.log(o)) | [resolve(2)]then((o) => console.log(o)) | [resolve(5)] ]。2、[ then(() => console.log(7))then(() => console.log(6)) ]。 第二次循环:检查延时队列 setTimeout(() => console.log(0)); 打印console.log(0)