class Promise {
constructor(fn) {
const that = this;
this.state = 'pending';
// value 变量用于保存 resolve 或者 reject 中传入的值
this.value = undefined;
this.reason = undefined;
// 用于保存 then 中的回调,因为当执行完 Promise 时状态可能还是等待中,这时候应该把 then 中的回调保存起来用于状态改变时使用
that.resolveCallbacks = [];
that.rejectCallbacks = [];
let reslove = value => {
if (that.state === 'pending') {
that.state = 'fulfilled';
that.value = value;
// 遍历回调数组并执行
that.resolveCallbacks.map(cb => cb(that.value))
}
}
let reject = value => {
if (that.state === 'pending') {
that.state = 'rejected';
that.reason = value;
// 遍历回调数组并执行
that.rejectCallbacks.map(cb => cb(that.value))
}
}
// 自动执行函数
try {
fn(reslove,reject);
} catch(e) {
reject(e);
}
}
// then
then(onFulfilled, onRejected) {
const that = this;
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v =>v;
onRejected = typeof onRejected === 'function' ? onRejected : e => {throw e};
switch(this.state) {
case 'pending':
this.resolveCallbacks.push(onFulfilled);
this.rejectCallbacks.push(onRejected);
case 'fulfilled':
onFulfilled(that.value);
break;
case 'rejected':
onRejected(that.value);
break;
default:
}
}
}
手写promise
最新推荐文章于 2023-05-30 08:44:50 发布