实现符合Promises/A+规范的Promise类需遵循状态不可逆、then链式调用、异步执行与错误捕获。核心包括:定义pending/fulfilled/rejected三种状态,通过resolve和reject函数变更状态并触发回调;then方法返回新Promise实例,支持onFulfilled与onRejected回调,并使用resolvePromise处理返回值,防止循环引用,递归解析嵌套Promise直至得到最终值。完整实现包含状态管理、回调队列、异步调度及类型安全判断,确保符合规范要求。

要实现一个符合 Promises/A+ 规范的 Promise 类,核心是理解其状态机机制、then 方法的处理逻辑以及异步解析流程。下面是一个简化但完全符合 Promises/A+ 规范的 Promise 实现,包含关键特性:状态管理、then 链式调用、异步执行、错误捕获和 resolvePromise 处理。
基本结构与状态定义
Promise 有三种状态:pending(等待)、fulfilled(成功)、rejected(失败)。一旦状态变更,不可逆。
- 初始状态为 pending
- 通过 resolve 改变为 fulfilled
- 通过 reject 改变为 rejected
- 状态变更后,所有后续的 resolve 或 reject 调用都无效
实现 then 方法
then 方法必须返回一个新的 Promise,以支持链式调用。它接收两个回调函数:onFulfilled 和 onRejected。
- 如果 onFulfilled 是函数,它在 Promise 成功时被调用
- 如果 onRejected 是函数,它在 Promise 失败时被调用
- then 的返回值用于决定新 Promise 的状态,需通过 resolvePromise 函数统一处理
- 支持异步注册,即在 pending 状态下将回调存入队列
处理嵌套 Promise 与 resolvePromise
当 then 的回调返回一个 Promise 时,需要等待其决议结果来决定外层 Promise 的状态。这是 Promises/A+ 的核心规则之一。
resolvePromise 函数的作用是:
- 判断 x 是否为 Promise 实例
- 防止循环引用(如 return self)
- 提取 then 方法并安全调用(防多次调用)
- 递归解析直到得到原始值
完整实现代码
以下是符合 Promises/A+ 规范的简易实现:
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function MyPromise(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.status === PENDING) {
this.value = value;
this.status = FULFILLED;
this.onFulfilledCallbacks.forEach(fn => fn());
}
};
const reject = (reason) => {
if (this.status === PENDING) {
this.reason = reason;
this.status = REJECTED;
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected'));
}
let called = false;
if ((typeof x === 'object' && x !== null) || 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);
}
}
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.status === FULFILLED) {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
}
if (this.status === REJECTED) {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
}
if (this.status === PENDING) {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
});
}
});
return promise2;
};
// 可选:添加 catch 方法
MyPromise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
};
// 可选:添加静态方法 resolve / reject
MyPromise.resolve = function(value) {
return new MyPromise(resolve => resolve(value));
};
MyPromise.reject = function(reason) {
return new MyPromise((_, reject) => reject(reason));
};
测试示例
验证基本功能:
new MyPromise((resolve) => {
setTimeout(() => resolve('hello'), 100);
})
.then(val => {
console.log(val); // hello
return val + ' world';
})
.then(val => {
console.log(val); // hello world
});
这个实现通过了大部分 Promises/A+ 测试用例(可用 promises-aplus-tests 工具验证),适合学习原理。
基本上就这些,关键是理解状态流转和 resolvePromise 的递归处理逻辑。










