class myPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
// 成功存放的数组
this.onResolvedCallbacks = [];
// 失败存放法数组
this.onRejectedCallbacks = [];
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
// 一旦resolve执行,调用成功数组的函数
this.onResolvedCallbacks.forEach(fn => fn());
}
};
let reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
// 一旦reject执行,调用失败数组的函数
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
let p2Resolve
let p2Reject
let p2 = new myPromise((resolve, reject) => {
p2Resolve = resolve
p2Reject = reject
})
if (this.state === 'fulfilled') {
onFulfilled(this.value);
p2Resolve()
};
if (this.state === 'rejected') {
onRejected(this.reason);
p2Reject()
};
// 当状态state为pending时
if (this.state === 'pending') {
// onFulfilled传入到成功数组
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value);
p2Resolve()
})
// onRejected传入到失败数组
this.onRejectedCallbacks.push(() => {
onRejected(this.reason);
p2Reject()
})
}
return p2
}
}
let p = new myPromise(function (resolve, reject) {
setTimeout(() => {
console.log('任务执行完了');
resolve()
}, 1500)
});
p.then(function (value) {
console.log('第一个成功回调')
}, function () {})
.then(function () {
console.log('第二个成功回调')
}, function () {});