class Promise {
constructor(executor) {
// 1.定义三个状态变量
this.PENDING = 'pengding';
this.FULFILLED = 'fufilled';
this.REJECTED = 'rejected';
// 2.初始状态是pending
this.state = this.PENDING
// 3.存储结果只或错误原因
this.value = undefined;
this.reason = undefined;
// 4.存储成功和失败的回调函数
this.onFUlfilledCallbacks = [];
this.onRejectedCallbacks = [];
// 5.处理Promise状态变更
const resolve = (value) => {
if (this.state === this.PENDING) {
this.state = this.FULFILLED;
this.value = value;
// 执行所有成功回调
this.onFUlfilledCallbacks.forEach((callback) => callback(value))
}
}
const reject = (reason) => {
if (this.state === this.PENDING) {
this.state = this.REJECTED;
this.reason = reason;
// 执行所有失败回调
this.onRejectedCallbacks.forEach((callback) => callback(reason))
}
}
// 6.执行executor 函数
try {
executor(resolve, reject);
} catch (error) {
reject(error); // 如果executor 抛出异常,进入拒绝状态
}
}
then(onFulfilled, onRejected) {
// 返回一个新的Promise 实例,用来实现链式调用
return new Promise((resolve, reject) => {
// 如果当前 Promise 已经 fulfilled,则直接执行成功回调
if (this.state === this.FULFILLED) {
setTimeout(() => {
try {
const result = onFulfilled(this.value); // 调用成功回调
resolve(result); // 处理回调返回值
} catch (error) {
reject(error); // 如果回调抛出异常,则执行reject
}
})
}
// 如果当前 Promise 已经rejected,则直接执行失败回调
if (this.state === this.REJECTED) {
setTimeout(() => {
try {
const result = onRejected(this.reason); // 调用失败回调
resolve(result) // 处理回调返回值
} catch (error) {
reject(error); // 如果回调抛出异常,则执行reject
}
})
}
// 如果当前 Promise 是pending,则先存储回调函数,等待状态改变后再执行
if (this.state === this.PENDING) {
this.onFUlfilledCallbacks.push(() => {
setTimeout(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
})
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
});
});
})
}
})
}
catch(onRejected){
return this.then(null,onRejected)
}
}