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

要实现一个符合 Promise A+ 规范 的 JavaScript 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) {
// 处理可选参数
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;
};
该函数处理 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);
}
}
虽然不是 A+ 必须,但添加这些方法提升实用性。
// 简化版 catch
MyPromise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
};
// 简化版 finally
MyPromise.prototype.finally = function(callback) {
return this.then(
value => MyPromise.resolve(callback()).then(() => value),
reason => MyPromise.resolve(callback()).then(() => { throw reason; })
);
};
// 静态 resolve / reject
MyPromise.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库?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号