实现符合Promises/A+规范的Promise类需遵循状态不可逆、then链式调用、异步执行与错误捕获。核心包括:定义pending/fulfilled/rejected三种状态,通过resolve和reject函数变更状态并触发回调;then方法返回新Promise实例,支持onFulfilled与onRejected回调,并使用resolvePromise处理返回值,防止循环引用,递归解析嵌套Promise直至得到最终值。完整实现包含状态管理、回调队列、异步调度及类型安全判断,确保符合规范要求。

要实现一个符合 Promises/A+ 规范的 Promise 类,核心是理解其状态机机制、then 方法的处理逻辑以及异步解析流程。下面是一个简化但完全符合 Promises/A+ 规范的 Promise 实现,包含关键特性:状态管理、then 链式调用、异步执行、错误捕获和 resolvePromise 处理。
Promise 有三种状态:pending(等待)、fulfilled(成功)、rejected(失败)。一旦状态变更,不可逆。
then 方法必须返回一个新的 Promise,以支持链式调用。它接收两个回调函数:onFulfilled 和 onRejected。
当 then 的回调返回一个 Promise 时,需要等待其决议结果来决定外层 Promise 的状态。这是 Promises/A+ 的核心规则之一。
resolvePromise 函数的作用是:
以下是符合 Promises/A+ 规范的简易实现:
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function MyPromise(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 (err) {
reject(err);
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected'));
}
let called = false;
if ((typeof x === 'object' && x !== null) || 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);
}
}
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.status === FULFILLED) {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
}
if (this.status === REJECTED) {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
}
if (this.status === PENDING) {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
}, 0);
});
}
});
return promise2;
};
// 可选:添加 catch 方法
MyPromise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
};
// 可选:添加静态方法 resolve / reject
MyPromise.resolve = function(value) {
return new MyPromise(resolve => resolve(value));
};
MyPromise.reject = function(reason) {
return new MyPromise((_, reject) => reject(reason));
};
验证基本功能:
new MyPromise((resolve) => {
setTimeout(() => resolve('hello'), 100);
})
.then(val => {
console.log(val); // hello
return val + ' world';
})
.then(val => {
console.log(val); // hello world
});
这个实现通过了大部分 Promises/A+ 测试用例(可用 promises-aplus-tests 工具验证),适合学习原理。
基本上就这些,关键是理解状态流转和 resolvePromise 的递归处理逻辑。
以上就是实现一个符合Promises/A+规范的Promise类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号