事件循环与 Promise

3 阅读4分钟

引入

先看一段常见的代码:

console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);

这里输出的顺序为 1 3 2。明明 setTimeout 的延迟是 0,为什么排在了最后呢?

因为 JS 是单线程的,只有一个调用栈,一次只能执行一件事。setTimeout 的回调不会立刻执行,而是被放入了队列,等待当前代码执行结束,才会执行。

这个排队 + 轮转的机制就是 事件循环 。

三个概念

调用栈 Call Stack

正在执行的函数,同步代码就是在栈上运行的。

function a() { b(); }
function b() { console.log('b'); }
a();
// 栈:[a] → [a, b] → 打印 → [a] → []

宏任务队列 Macrotask Queue

装的都是回调,比如:

  • setTimeout / setInterval 的回调
  • DOM 事件回调
  • I/O 完成回调
  • MessageChannel / postMessage

微任务队列 Microtask Queue

  • Promise.then / .catch / .finally 的回调
  • queueMicrotask(fn)
  • MutationObserver 的回调
  • await 下面的代码

微任务的优先级比宏任务高。

另外用一个表格对比一下,更方便记忆:

宏任务微任务
setTimeout / setInterval 的回调then / catch / finally 的回调
DOM 事件回调(click、scroll)queueMicrotask(fn)
I/O 完成回调MutationObserver 的回调
postMessage、MessageChannelawait 下面的代码

事件循环的规则

执行完一个宏任务后,把微任务队列 清空,然后才进入下一个循环,接取下一个宏任务。

graph TD
A["执行一个宏任务(包括同步代码)"] --> B["清空微任务队列(清到空为止,期间产生的微任务也要执行)"]
B --> C["需要的话渲染页面"]

可以这么理解:同步代码本身,可以视作第一个宏任务。

经典案例

下面这段代码:

console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');

输出:1 4 3 2

每个步骤发生了什么:

步骤发生了什么
1console.log('1') → 打印 1
2setTimeout → 回调进宏任务队列
3Promise.then → 回调进微任务队列
4console.log('4') → 打印 4
5同步代码跑完 → 清空微任务 → 打印 3
6取下一个宏任务 → 打印 2

链式 then

setTimeout(() => console.log('A'), 0);

Promise.resolve()
  .then(() => console.log('B'))
  .then(() => console.log('C'));

console.log('D');

输出:D B C A

别忘了:事件循环会清空微任务队列,中途出现的新的微任务也会清空。所以这里先执行同步代码,然后执行微任务,然后最后宏任务。

async / await 的顺序

async function async1() {
  console.log('A');
  await async2();
  console.log('B');
}

async function async2() {
  console.log('C');
}

console.log('D');
async1();
console.log('E');

输出:D A C E B

这里有一个规则:await 右边的东西会立刻同步执行,await 下面的东西相当于 then 的回调,进入了微任务队列。

步骤打印
console.log('D')D
调用 async1() → 打印 AA
执行 await async2() → 先同步执行 async2() → 打印 CC
await 之后(console.log('B'))被挂起,进微任务队列—
async1() 返回,继续执行 console.log('E')E
同步代码结束 → 清空微任务 → 打印 BB

Promise 基础

三种状态

graph LR
A["pending(进行中)"]
B["fullfilled(成功)"]
C["rejected(失败)"]

A --resolve--> B
A --reject--> C

状态一旦改变了,就不可以更改了。例如:

const p = new Promise((resolve, reject) => {
  resolve(1);
  reject(2);  // ← 无效,已经 fulfilled 了
  resolve(3);  // ← 也无效
});
p.then((v) => console.log(v)); // 1

.then 返回新 Promise

Promise.resolve(1)
  .then((v) => {
    console.log(v); // 1
    return v + 1;   // 返回值会成为下一个 then 的参数
  })
  .then((v) => console.log(v)); // 2

如果 then 里抛错,或者返回 rejected 的 Promise,会跳到 catch。

Promise.resolve()
  .then(() => { throw new Error('错了'); })
  .then(() => console.log('不会执行'))
  .catch((e) => console.log('捕获:', e.message));

这叫错误穿透:中间没有 catch 的话,错误会一直往链尾传。

手写 Promise.all

首先想清楚他的结果:

  • 全部成功:resolve 一个结果数组,顺序和输入的一致
  • 任意一个失败:立刻 reject,只带第一个错误
  • 空数组:立刻 resolve 空数组
  • 数组里面如果出现非 Promise 值也需要处理

那么就可以开始实现了:

function myAll(promises) {
  return new Promise((resolve, reject) => {
    const list = Array.from(promises);
    const result = new Array(list.length);
    let remaining = list.length;

    if (remaining === 0) return resolve([]);

    list.forEach((item, index) => {
      // Promise.resolve 把非 Promise 值也包成 Promise
      Promise.resolve(item).then(
        (value) => {
          result[index] = value; // 用下标,保证顺序
          remaining--;
          if (remaining === 0) resolve(result);
        },
        (error) => reject(error), // 第一个失败立刻整体失败
      );
    });
  });
}

常见问题

  1. 为什么要用索引?因为 Promise 的完成顺序不可控,但是结果必须按照输入顺序排列。
  2. 为什么要计数 remaining?因为无法预知哪个最后完成,只能数还剩下几个。
  3. 为什么用 Promise.resolve(item)?为了让普通的数据,比如 1、a 这种非 Promise 值也可以被 .then。
  4. 为什么失败直接 reject?因为整体立刻失败,不需要等待剩下的。

练习

1. 输出顺序

console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);

输出结果:

1
4
3
2

2. 输出顺序

setTimeout(() => console.log('A'), 0);

Promise.resolve()
  .then(() => console.log('B'))
  .then(() => console.log('C'));

console.log('D');

输出结果:

D
B
C
A

3. 输出顺序

async function async1() {
  console.log('A');
  await async2();
  console.log('B');
}

async function async2() {
  console.log('C');
}

console.log('D');
async1();
console.log('E');

输出:

D
A
C
E
B