实现一个符合 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 处理、状态不可逆变更、异步执行以及错误捕获的要求。
Promise 有三种状态:pending、fulfilled、rejected,状态只能从 pending 变为 fulfilled 或 rejected,且一旦确定不可更改。
构造函数接收一个 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);
}
}
then 是 Promise A+ 的核心,必须返回一个新的 Promise,以支持链式调用。它接收两个可选参数:onFulfilled 和 onRejected。
关键逻辑在处理返回值 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;
};
这个函数处理 then 中回调返回的值 x,判断是否为 Promise 或 thenable 对象,决定如何 resolve 新的 promise2。
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);
}
}
虽然 Promise A+ 只规定了 then,但完整的库通常包含以下静态方法:
例如 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 工具验证兼容性。
以上就是如何实现一个符合Promise A+规范的完整Promise库?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号