function Promise(executor) {
this.state = 'pending'; // Promise的状态
this.value = undefined; // 保存状态为resolved时的值
this.reason = undefined; // 保存状态为rejected时的原因
// 保存 then 方法中的回调
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
// 状态转变为resolved时的函数
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'resolved';
this.value = value;
this.onResolvedCallbacks.forEach(callback => callback(value));
}
};
// 状态转变为rejected时的函数
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason));
}
};
// 立即执行executor,传入resolve和reject函数
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
// then 方法用于注册回调函数
Promise.prototype.then = function(onResolved, onRejected) {
if (this.state === 'resolved') {
onResolved(this.value);
}
if (this.state === 'rejected') {
onRejected(this.reason);
}
if (this.state === 'pending') {
this.onResolvedCallbacks.push(onResolved);
this.onRejectedCallbacks.push(onRejected);
}
};
// 使用示例
const myPromise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
// 成功时调用 resolve('成功值')
// 失败时调用 reject('失败原因')
resolve('操作成功完成');
}, 1000);
});
myPromise.then(
(value) => console.log(value), // 成功回调
(reason) => console.error(reason) // 失败回调
);