Promise 内部机制与微任务队列
手写 Promise 核心逻辑,理解 then 链的微任务调度、异步回调注册与错误冒泡。 · 难度:入门 · +10XP
Promise 内部机制与微任务队列
Promise 的 then/catch 并不是同步执行的,而是通过微任务队列(Microtask Queue)调度。本教程将用 100 行代码实现一个简约 Promise,包含状态机、then 链、值穿透和异步执行。通过理解微任务与宏任务的执行顺序(先微再宏),你将明白为什么 setTimeout(0) 晚于 Promise.resolve().then()。
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.handlers = [];
const resolve = (value) => {
if (this.state !== 'pending') return;
this.state = 'fulfilled';
this.value = value;
this.handlers.forEach(h => h.onFulfilled(value));
};
executor(resolve);
}
then(onFulfilled) {
return new MyPromise((resolve) => {
if (this.state === 'fulfilled') {
queueMicrotask(() => resolve(onFulfilled(this.value)));
} else {
this.handlers.push({ onFulfilled: (v) => queueMicrotask(() => resolve(onFulfilled(v))) });
}
});
}
}