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

实现一个符合 Promise A+ 规范的 Promise 类,核心在于理解其状态机制、异步解析流程以及 then 方法的处理规则。下面是一个简化但符合规范关键点的实现,帮助你掌握原理。
1. 状态定义与基本结构
Promise 有三种状态:pending(等待)、fulfilled(成功)、rejected(失败)。状态一旦改变,不可逆。
初始化为 pending只能从 pending → fulfilled 或 pending → rejected需要存储成功值 value 和失败原因 reason支持多次调用 then,所以需要维护回调队列
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); }}
2. 实现 then 方法
then 方法必须返回一个新的 Promise,实现链式调用。这是 Promise A+ 的核心要求之一。
根据当前状态决定执行 onFulfilled 或 onRejected如果还在 pending,把回调加入队列返回新 Promise,实现链式调用
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;};
3. 处理返回值 x(resolvePromise)
这个函数是 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); }}
4. 补充常用方法(可选)
虽然不是 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类?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1524182.html
微信扫一扫
支付宝扫一扫