实现符合 Promises/A+ 规范的 Promise 类需掌握其核心机制:1. 状态不可逆(pending → fulfilled/rejected);2. 构造函数立即执行 executor 并接收 resolve/reject 函数;3. then 方法返回新 Promise,支持链式调用;4. 回调通过 queueMicrotask 异步执行;5. resolvePromise 解析返回值,处理对象或函数的 thenable 行为;6. 检测循环引用。该实现涵盖状态管理、异步延迟、错误捕获与链式传递,基本通过 A+ 测试。

要实现一个符合 Promises/A+ 规范的 Promise 类,核心是理解其状态机制、then 方法的处理逻辑以及异步解析流程。下面是一个精简但完整、符合规范关键点的实现。
Promise 的三种状态
Promise 有三种状态:
pending:初始状态,可变 fulfilled:成功状态,不可逆 rejected:失败状态,不可逆
状态一旦从 pending 变为 fulfilled 或 rejected,就不能再改变。
构造函数与状态管理
创建 Promise 实例时,传入一个执行器函数(executor),它立即执行,并接收 resolve 和 reject 两个函数作为参数。
class MyPromise { constructor(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 (error) { reject(error); } }}
实现 then 方法
then 方法用于注册成功和失败的回调,且必须返回一个新的 Promise,以支持链式调用。
关键点包括:
onFulfilled 和 onRejected 是可选函数 回调必须异步延迟执行(使用 queueMicrotask 或 setTimeout) 处理返回值 x,调用 resolvePromise 进行解析
then(onFulfilled, onRejected) { // 处理可选参数 onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val; onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; }; // 返回新的 Promise 实现链式调用 const promise2 = new MyPromise((resolve, reject) => { const handleCallback = (callback, status, data) => { queueMicrotask(() => { try { const x = callback(data); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); } }); }; if (this.status === 'fulfilled') { handleCallback(onFulfilled, this.status, this.value); } else if (this.status === 'rejected') { handleCallback(onRejected, this.status, this.reason); } else { // pending 状态,缓存回调 this.onFulfilledCallbacks.push(() => handleCallback(onFulfilled, 'fulfilled', this.value)); this.onRejectedCallbacks.push(() => handleCallback(onRejected, 'rejected', this.reason)); } }); return promise2;}
resolvePromise 辅助函数
这个函数决定如何根据 x 的类型来 resolve 新的 Promise,是 Promises/A+ 的核心逻辑之一。
function resolvePromise(promise, x, resolve, reject) { if (promise === 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(promise, 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); }}
基本上就这些。这个实现涵盖了 Promises/A+ 的主要要求:状态管理、then 链式调用、异步执行、错误捕获和循环引用检测。虽然省略了一些边界情况的极致优化,但它能通过大部分 A+ 测试套件(如 promises-aplus-tests)。
以上就是怎样实现一个符合 Promises/A+ 规范的 Promise 类?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1528375.html
微信扫一扫
支付宝扫一扫