实现一个符合 Promise A+ 规范的 Promise 类,需定义 pending、fulfilled、rejected 三种不可逆状态,通过 resolve 和 reject 函数改变状态并执行对应回调;then 方法返回新 Promise 实现链式调用,根据当前状态异步执行 onFulfilled 或 onRejected,并将结果传入 resolvePromise 处理;resolvePromise 函数递归解析返回值 x,避免循环引用并正确处理 thenable 对象;最后补充 resolve、reject、catch、finally 等常用方法以增强实用性。

实现一个符合 Promise A+ 规范的 Promise 类,核心在于理解其状态机制、异步解析流程以及 then 方法的处理规则。下面是一个简化但符合规范关键点的实现,帮助你掌握原理。
Promise 有三种状态:pending(等待)、fulfilled(成功)、rejected(失败)。状态一旦改变,不可逆。
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 (error) {
reject(error);
}
}then 方法必须返回一个新的 Promise,实现链式调用。这是 Promise A+ 的核心要求之一。
MyPromise.prototype.then = function(onFulfilled, onRejected) {
// 处理穿透,比如 .then().then(value => ...)
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') {
queueMicrotask(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (this.state === 'rejected') {
queueMicrotask(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => {
queueMicrotask(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
this.onRejectedCallbacks.push(() => {
queueMicrotask(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
}
});
return promise2;
};这个函数是 Promise A+ 规范中最复杂的部分,用于处理 then 回调返回的值 x,决定如何解析新 Promise。
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
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);
}
}虽然不是 A+ 规范强制要求,但可以添加一些静态方法增强实用性。
MyPromise.resolve = function(value) {
return new MyPromise(resolve => resolve(value));
};
MyPromise.reject = function(reason) {
return new MyPromise((resolve, reject) => reject(reason));
};
MyPromise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
};
MyPromise.prototype.finally = function(callback) {
return this.then(
value => MyPromise.resolve(callback()).then(() => value),
reason => MyPromise.resolve(callback()).then(() => { throw reason; })
);
};基本上就这些。这个实现覆盖了 Promise A+ 的主要逻辑:状态管理、异步任务队列、then 链式调用和 resolvePromise 的递归解析。要完全通过官方测试套件(promises-aplus-tests),还需更严格的边界处理,但上述代码已能体现核心思想。
以上就是如何实现一个符合Promise A+规范的Promise类?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号