FROM THE BOOKSHELF / A PAGE TO KEEP
Promise A+ 规范实现
发布于 2026-05-21
完整实现Promise A+规范,涵盖状态机转换、then链值传递与错误传递、决议程序递归平铺算法及Promise.all/race/any实现

Promise 是 JavaScript 异步编程的基石。Promises/A+ 规范定义了 then 方法的行为和状态转换规则,ECMAScript 规范在此基础上扩展了 catch、finally、all、race 等静态方法。本文将从零实现一个完全符合 A+ 规范的 Promise,深入分析 V8 中 Promise 的微任务调度机制,并对比原生 Promise 与手写版本的性能差异。
目录
- Promise 状态机模型
- 从零实现 Promise A+
- then 的链式调用与值穿透
- Resolution Procedure 解析算法
- 静态方法实现
- V8 中的 Promise 优化
- 错误处理与未捕获拒绝
- 实战案例
- 深度追问
- 总结表格
1. Promise 状态机模型
resolve(value)
┌──────────────────────┐
│ ▼
┌───────┐ ┌──────────┐
│Pending│ │Fulfilled │ → 不可再变
└───┬───┘ └──────────┘
│
│ reject(reason)
│ ┌──────────┐
└───────────────►│ Rejected │ → 不可再变
└──────────┘
规范要求(A+ §2.1):
- pending 可转为 fulfilled 或 rejected
- fulfilled/rejected 后状态不可变
- fulfilled 必须有一个不可变的 value
- rejected 必须有一个不可变的 reason
2. 从零实现 Promise A+
// 代码示例 1:完整的 Promise A+ 实现
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
#state = PENDING;
#value = undefined;
#handlers = []; // { onFulfilled, onRejected, resolve, reject }
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('Promise resolver must be a function');
}
const resolve = (value) => {
this.#transition(FULFILLED, value);
};
const reject = (reason) => {
this.#transition(REJECTED, reason);
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
#transition(state, value) {
if (this.#state !== PENDING) return; // 状态不可逆
this.#state = state;
this.#value = value;
this.#executeHandlers();
}
#executeHandlers() {
if (this.#state === PENDING) return;
// 异步执行所有回调(A+ §2.2.4:必须异步调用)
queueMicrotask(() => {
while (this.#handlers.length) {
const handler = this.#handlers.shift();
this.#handle(handler);
}
});
}
#handle({ onFulfilled, onRejected, resolve, reject }) {
const callback = this.#state === FULFILLED ? onFulfilled : onRejected;
// 值穿透:如果没有对应回调,直接传递
if (typeof callback !== 'function') {
if (this.#state === FULFILLED) {
resolve(this.#value);
} else {
reject(this.#value);
}
return;
}
try {
const result = callback(this.#value);
resolvePromise(resolve, reject, result);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
// A+ §2.2.7:then 必须返回新 Promise
return new MyPromise((resolve, reject) => {
this.#handlers.push({ onFulfilled, onRejected, resolve, reject });
this.#executeHandlers();
});
}
catch(onRejected) {
return this.then(null, onRejected);
}
finally(onFinally) {
return this.then(
value => MyPromise.resolve(onFinally()).then(() => value),
reason => MyPromise.resolve(onFinally()).then(() => { throw reason; })
);
}
}
3. then 的链式调用与值穿透
// 代码示例 2:值穿透行为
MyPromise.resolve(1)
.then(2) // 2 不是函数,被忽略
.then(null) // null 不是函数,被忽略
.then(v => {
console.log(v); // 1 — 值穿透了!
});
// 代码示例 3:链式 then 的返回值传递
MyPromise.resolve('start')
.then(v => v + ' → step1')
.then(v => v + ' → step2')
.then(v => {
console.log(v); // "start → step1 → step2"
});
then 返回 Promise 的情况
// 代码示例 4:then 回调返回 Promise
MyPromise.resolve(1)
.then(v => {
return new MyPromise((resolve) => {
setTimeout(() => resolve(v * 10), 100);
});
})
.then(v => {
console.log(v); // 10(等待内部 Promise resolve)
});
4. Resolution Procedure 解析算法
A+ §2.3 定义了 Promise Resolution Procedure [[Resolve]](promise, x):
// 代码示例 5:完整的 resolvePromise 实现
function resolvePromise(resolve, reject, x) {
// §2.3.1:如果 promise 和 x 指向同一对象 → TypeError
// (在实际实现中需要传入 promise2 做检查)
// §2.3.2:如果 x 是 Promise 实例
if (x instanceof MyPromise) {
x.then(resolve, reject);
return;
}
// §2.3.3:如果 x 是对象或函数(thenable)
if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
let called = false; // 防止多次调用
try {
const then = x.then; // §2.3.3.1:获取 then
if (typeof then === 'function') {
// §2.3.3.3:作为 x 的方法调用 then
then.call(
x,
(y) => {
if (called) return;
called = true;
resolvePromise(resolve, reject, y); // 递归解析
},
(r) => {
if (called) return;
called = true;
reject(r);
}
);
} else {
// §2.3.3.4:then 不是函数,直接 resolve
resolve(x);
}
} catch (err) {
if (!called) {
reject(err);
}
}
} else {
// §2.3.4:x 是原始值,直接 resolve
resolve(x);
}
}
5. 静态方法实现
// 代码示例 6:静态方法
// Promise.resolve
MyPromise.resolve = function(value) {
if (value instanceof MyPromise) return value;
return new MyPromise(resolve => resolve(value));
};
// Promise.reject
MyPromise.reject = function(reason) {
return new MyPromise((_, reject) => reject(reason));
};
// Promise.all
MyPromise.all = function(promises) {
return new MyPromise((resolve, reject) => {
const results = [];
let remaining = 0;
const iterable = [...promises];
if (iterable.length === 0) {
resolve(results);
return;
}
iterable.forEach((promise, index) => {
remaining++;
MyPromise.resolve(promise).then(
value => {
results[index] = value;
if (--remaining === 0) resolve(results);
},
reject // 一个失败就全部失败
);
});
});
};
// Promise.race
MyPromise.race = function(promises) {
return new MyPromise((resolve, reject) => {
for (const promise of promises) {
MyPromise.resolve(promise).then(resolve, reject);
}
});
};
// Promise.allSettled
MyPromise.allSettled = function(promises) {
return new MyPromise((resolve) => {
const results = [];
let remaining = 0;
const iterable = [...promises];
if (iterable.length === 0) {
resolve(results);
return;
}
iterable.forEach((promise, index) => {
remaining++;
MyPromise.resolve(promise).then(
value => {
results[index] = { status: 'fulfilled', value };
if (--remaining === 0) resolve(results);
},
reason => {
results[index] = { status: 'rejected', reason };
if (--remaining === 0) resolve(results);
}
);
});
});
};
// Promise.any
MyPromise.any = function(promises) {
return new MyPromise((resolve, reject) => {
const errors = [];
let remaining = 0;
const iterable = [...promises];
if (iterable.length === 0) {
reject(new AggregateError([], 'All promises were rejected'));
return;
}
iterable.forEach((promise, index) => {
remaining++;
MyPromise.resolve(promise).then(
resolve, // 一个成功就成功
reason => {
errors[index] = reason;
if (--remaining === 0) {
reject(new AggregateError(errors, 'All promises were rejected'));
}
}
);
});
});
};
6. V8 中的 Promise 优化
PromiseHook 与 async_hooks
// 代码示例 7:V8 内部的 Promise 优化
// V8 不使用 Array 存储回调,而是使用 PromiseReaction 链表
// 当只有一个 then 时,直接存储在 Promise 对象上(快路径)
// Node.js async_hooks 可以追踪 Promise 生命周期
const { createHook, executionAsyncId, triggerAsyncId } = require('async_hooks');
const hook = createHook({
init(asyncId, type, triggerAsyncId, resource) {
if (type === 'PROMISE') {
console.log(`Promise ${asyncId} created by ${triggerAsyncId}`);
}
},
before(asyncId) { /* 回调执行前 */ },
after(asyncId) { /* 回调执行后 */ },
destroy(asyncId) { /* Promise 被 GC */ }
});
hook.enable();
V8 的零成本 await 优化
// 代码示例 8:V8 优化的 await
// ES2020 之前:await 需要 2 个微任务 tick
// ES2020 之后:如果 await 的值是 native Promise,只需 1 tick
async function optimized() {
// V8 检测到 p 是原生 Promise,跳过 PromiseResolve 包装
const p = Promise.resolve(42);
return await p; // 只需 1 个微任务
}
// 对比自定义 thenable
async function notOptimized() {
const thenable = { then(resolve) { resolve(42); } };
return await thenable; // 需要额外的微任务来处理 thenable
}
7. 错误处理与未捕获拒绝
// 代码示例 9:未处理的 rejection 检测
// 浏览器
window.addEventListener('unhandledrejection', event => {
console.error('Unhandled:', event.reason);
event.preventDefault(); // 阻止默认日志
});
window.addEventListener('rejectionhandled', event => {
console.log('Late handled:', event.reason);
});
// Node.js
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled:', reason);
});
process.on('rejectionHandled', (promise) => {
console.log('Late handled');
});
错误恢复模式
// 代码示例 10:优雅的错误处理链
function fetchWithRetry(url, options = { retries: 3, delay: 1000 }) {
return new Promise((resolve, reject) => {
let attempts = 0;
function attempt() {
fetch(url)
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(resolve)
.catch(err => {
attempts++;
if (attempts >= options.retries) {
reject(new Error(`Failed after ${attempts} attempts: ${err.message}`));
} else {
setTimeout(attempt, options.delay * Math.pow(2, attempts - 1));
}
});
}
attempt();
});
}
8. 实战案例
实战案例 1:并发控制器
class PromisePool {
#concurrency;
#running = 0;
#queue = [];
constructor(concurrency = 5) {
this.#concurrency = concurrency;
}
async add(taskFn) {
if (this.#running >= this.#concurrency) {
// 等待一个位置释放
await new Promise(resolve => this.#queue.push(resolve));
}
this.#running++;
try {
return await taskFn();
} finally {
this.#running--;
if (this.#queue.length > 0) {
const next = this.#queue.shift();
next(); // 释放下一个等待者
}
}
}
async addAll(taskFns) {
return Promise.all(taskFns.map(fn => this.add(fn)));
}
}
// 使用
const pool = new PromisePool(3);
const urls = Array.from({ length: 100 }, (_, i) => `/api/item/${i}`);
const results = await pool.addAll(
urls.map(url => () => fetch(url).then(r => r.json()))
);
实战案例 2:超时与取消
// Promise 超时包装
function withTimeout(promise, ms, message = 'Operation timed out') {
const timeout = new Promise((_, reject) => {
const id = setTimeout(() => {
reject(new Error(message));
}, ms);
// 如果原始 Promise 先完成,清除定时器
promise.finally(() => clearTimeout(id));
});
return Promise.race([promise, timeout]);
}
// AbortController 集成
function cancellableFetch(url, options = {}) {
const controller = new AbortController();
const promise = fetch(url, {
...options,
signal: controller.signal
});
return {
promise,
cancel: () => controller.abort()
};
}
// 组合使用
const { promise, cancel } = cancellableFetch('/api/data');
const result = await withTimeout(promise, 5000);
实战案例 3:Promise 缓存 / 请求去重
function createRequestDeduper() {
const inflight = new Map();
return async function dedupedFetch(url, options) {
const key = `${options?.method || 'GET'}:${url}`;
if (inflight.has(key)) {
return inflight.get(key); // 返回进行中的 Promise
}
const promise = fetch(url, options)
.then(r => r.json())
.finally(() => {
inflight.delete(key); // 完成后清除
});
inflight.set(key, promise);
return promise;
};
}
const dedupedFetch = createRequestDeduper();
// 同时发起 3 个相同请求,只会实际发送 1 次
const [r1, r2, r3] = await Promise.all([
dedupedFetch('/api/user/1'),
dedupedFetch('/api/user/1'),
dedupedFetch('/api/user/1'),
]);
// r1 === r2 === r3(同一个结果)
9. 深度追问
Q1:为什么 Promise A+ 规范要求 then 回调必须异步执行?
为了保证一致的执行顺序。如果同步执行,那么 promise.then(fn) 的行为会因 promise 当前状态不同而不同——已解决时同步调用 fn,未解决时异步调用。这种不确定性会导致难以调试的竞态条件(Zalgo 问题)。
Q2:Promise.resolve 和 new Promise(resolve => resolve(x)) 有区别吗?
当 x 是 Promise 实例时有区别:Promise.resolve(x) 直接返回 x 本身(同一引用),而 new Promise(resolve => resolve(x)) 会创建一个新 Promise 并跟踪 x 的状态(多一个微任务延迟)。
Q3:为什么 async 函数总是返回 Promise?
ECMAScript 规范(§15.8.3)定义 async 函数的 [[Call]] 内部方法会创建一个 Promise,函数体的同步返回值作为 resolve 参数,throw 的异常作为 reject 参数。这确保了 async 函数的调用者总是得到一致的异步接口。
10. 总结表格
| Promise 方法 | 行为 | 短路条件 |
|---|---|---|
Promise.all | 全部成功才成功 | 一个 reject 就 reject |
Promise.allSettled | 等待全部完成 | 无短路 |
Promise.race | 采用第一个完成的 | 第一个 settle |
Promise.any | 采用第一个成功的 | 一个 resolve 就 resolve |
| 概念 | 规范引用 | 关键行为 |
|---|---|---|
| 状态不可逆 | A+ §2.1 | fulfilled/rejected 后锁定 |
| 异步回调 | A+ §2.2.4 | then 回调必须异步 |
| 值穿透 | A+ §2.2.1/7 | 非函数参数被忽略 |
| thenable 协议 | A+ §2.3.3 | 支持任意实现互操作 |
| 防重入 | A+ §2.3.3.3.3 | called 标志位 |
| 性能对比 | 原生 Promise | 手写 Promise |
|---|---|---|
| 内存 | 56 bytes (V8) | ~200 bytes |
| then 注册 | 内联 PromiseReaction | Array push |
| 微任务调度 | C++ 层直接入队 | queueMicrotask |
| GC 优化 | 有 | 无 |
下一篇:08. 协作式多任务与异步语法糖