实现一个符合 Promise A+ 规范的 Promise 库,需定义 PENDING、FULFILLED、REJECTED 三种状态,构造函数执行 executor 并传入 resolve 和 reject 方法,通过 onFulfilledCallbacks 和 onRejectedCallbacks 存储异步回调;then 方法返回新 Promise,根据当前状态异步执行 onFulfilled 或 onRejected,并调用 resolvePromise 解析返回值 x;resolvePromise 函数处理 x 为 promise 或 thenable 的情况,防止循环引用并确保状态只改变一次;最后补充 MyPromise.resolve、reject、all、race 等静态方法以完善功能。整个实现需严格遵循规范对状态机、异步执行、错误捕获和链式调用的要求。

实现一个符合 Promise A+ 规范的 Promise 库,核心是理解并正确处理状态机、异步解析和 then 方法的链式调用。重点在于遵循规范中对 thenable 处理、状态不可逆变更、异步执行以及错误捕获的要求。
1. 定义基本状态与结构
Promise 有三种状态:pending、fulfilled、rejected,状态只能从 pending 变为 fulfilled 或 rejected,且一旦确定不可更改。
- 使用常量表示状态:PENDING = 'pending', FULFILLED = 'fulfilled', REJECTED = 'rejected'
- 每个 Promise 实例保存当前状态(this.state)、成功值(this.value)、失败原因(this.reason)
- 维护 onFulfilled 和 onRejected 回调队列,用于处理异步 resolve/reject 的情况
构造函数接收一个 executor 函数,立即执行,并传入 resolve 和 reject 方法:
function MyPromise(executor) {
this.state = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === PENDING) {
this.state = FULFILLED;
this.value = value;
this.onFulfilledCallbacks.forEach(fn => fn());
}
};
const reject = (reason) => {
if (this.state === PENDING) {
this.state = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
2. 实现 then 方法
then 是 Promise A+ 的核心,必须返回一个新的 Promise,以支持链式调用。它接收两个可选参数:onFulfilled 和 onRejected。
- 根据当前状态决定如何处理回调:同步 resolved 就直接执行,异步则暂存到队列
- 如果 onFulfilled/onRejected 是函数,必须异步执行(使用 setTimeout 模拟微任务)
- 返回新 Promise,其状态由回调的返回值或异常决定
关键逻辑在处理返回值 x,需调用 resolvePromise 函数进行“解析”:
MyPromise.prototype.then = function(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val;
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };
const promise2 = new MyPromise((resolve, reject) => {
if (this.state === FULFILLED) {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
}
if (this.state === REJECTED) {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
}
if (this.state === PENDING) {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
}
});
return promise2;
};
3. 实现 resolvePromise 辅助函数
这个函数处理 then 中回调返回的值 x,判断是否为 Promise 或 thenable 对象,决定如何 resolve 新的 promise2。
- 如果 x 和 promise2 相同,抛出 TypeError(防止循环引用)
- 如果 x 是对象或函数,尝试读取其 then 属性(注意可能抛错)
- 如果 x 有 then 方法且是函数,则认为是 thenable,将其作为 Promise 处理
- 否则将 x 作为普通值 resolve
function resolvePromise(promise2, x, resolve, reject) {
if (x === promise2) {
return reject(new TypeError('Chaining cycle detected'));
}
let called = false;
if ((x !== null && typeof x === 'object') || typeof x === 'function') {
try {
const then = x.then;
if (typeof then === 'function') {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, r => {
if (called) return;
called = true;
reject(r);
});
} else {
resolve(x);
}
} catch (e) {
if (called) return;
called = true;
reject(e);
}
} else {
resolve(x);
}
}
4. 补充常用方法
虽然 Promise A+ 只规定了 then,但完整的库通常包含以下静态方法:
- MyPromise.resolve(value):返回一个 resolved 状态的 Promise
- MyPromise.reject(reason):返回一个 rejected 状态的 Promise
- MyPromise.all(promises):全部完成才 resolve,任意失败则 reject
- MyPromise.race(promises):首个完成的 Promise 决定结果
例如 all 的实现:
MyPromise.all = function(promises) {
return new MyPromise((resolve, reject) => {
const results = [];
let completedCount = 0;
const total = promises.length;
if (total === 0) {
resolve(results);
return;
}
for (let i = 0; i < total; i++) {
MyPromise.resolve(promises[i]).then(value => {
results[i] = value;
completedCount++;
if (completedCount === total) {
resolve(results);
}
}, reject);
}
});
};
基本上就这些。只要严格按照 Promise A+ 规范处理状态流转、回调调度和链式解析,就能实现一个合规且可用的 Promise 库。测试时建议使用官方 promises-aplus-tests 工具验证兼容性。










