答案:实现符合Promise A+规范的Promise库需核心处理状态机、then链式调用与resolvePromise解析逻辑,支持异步回调、错误捕获及循环引用检测,确保状态不可逆、then返回新Promise并正确处理值类型。

要实现一个符合 Promise A+ 规范 的 JavaScript Promise 库,核心是理解并正确实现状态机、then 方法的链式调用以及异步解析流程。以下是一个精简但完整、符合规范的实现,包含关键机制和注释说明。
1. 基本结构与状态定义
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); }}
2. 实现 then 方法
then 方法必须返回一个新的 Promise,以支持链式调用。这是 Promise A+ 的核心要求之一。
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;};
3. 核心:resolvePromise 函数
该函数处理 x 的值类型,判断是否为 Promise 或具有 then 方法的对象,并递归解析,确保符合 A+ 规范中的“Thenable”处理逻辑。
立即学习“Java免费学习笔记(深入)”;
function resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise')); } 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+ 必须,但添加这些方法提升实用性。
// 简化版 catchMyPromise.prototype.catch = function(onRejected) { return this.then(null, onRejected);};// 简化版 finallyMyPromise.prototype.finally = function(callback) { return this.then( value => MyPromise.resolve(callback()).then(() => value), reason => MyPromise.resolve(callback()).then(() => { throw reason; }) );};// 静态 resolve / rejectMyPromise.resolve = function(value) { return new MyPromise(resolve => resolve(value));};MyPromise.reject = function(reason) { return new MyPromise((_, reject) => reject(reason));};
基本上就这些。这个实现涵盖了 Promise A+ 规范的核心:状态管理、then 的链式返回、异步执行、错误捕获、Thenable 解析和循环引用检测。你可以通过 promises-aplus-tests 来验证其合规性。关键是理解 resolvePromise 如何统一处理各种返回值,保证 Promise 链的稳定性。
以上就是如何实现一个符合Promise A+规范的JavaScript Promise库?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1525169.html
微信扫一扫
支付宝扫一扫