面试官:实现一个自己的 Promise 吧!(WIP)
今天面试官问了我这个问题,写得磕磕绊绊的,最后也没写出来,复盘一下。
Promise 的本质:回调函数,被封装在内部。
参考这篇文章,我先实现了一个基础的 Promise:
class MyPromise {
static cbs: Array<(val: any) => any> = [];
static errorCbs: Array<(err: any) => any> = [];
status: 'pending' | 'fulfilled' | 'rejected' = 'pending';
data: any = undefined;
constructor(callback: (resolve: MyPromise['resolve'], reject: MyPromise['reject']) => any) {
try {
callback(this.resolve, this.reject);
} catch (e) {
this.reject(e);
}
}
resolve = (val: any) => {
this.status = 'fulfilled';
setTimeout(() => {
// 加上 setTimeout 是为了确保 cbs 长度大于0
MyPromise.cbs.forEach(f => f(val));
});
this.data = val;
}
reject = (reason: any) => {
this.status = 'rejected';
setTimeout(() => {
MyPromise.errorCbs.forEach(f => f(reason));
})
this.data = reason;
}
then = (fun: (data: any) => any) => {
MyPromise.cbs.push(fun);
return this;
}
catch = (onRejected: (err: any) => any) => {
setTimeout(() => {
MyPromise.errorCbs.push(onRejected);
});
return this;
}
}