手写Promise
class MyPromise { constructor(excutorCallBack) { this.status = "pending"; this.value = undefined; this.resolveCallbackArr = []; this.rejectCallbackArr = []; const resolveFn = (result) => { // 这里加setTimeout延时,主要是为了让then里面的回调先被添加到对应的数组中,之后有回调可以循环执行 setTimeout(() => { if (this.status === "pending") { this.status = "resolved"; this.value = result; if (this.resolveCallbackArr.length) this.resolveCallbackArr.forEach(item => item(this.value)); }; }, 0) } const rejectFn = (reason) => { // 这里加setTimeout延时,主要是为了让then里面的回调先被添加到对应的数组中,之后有回调可以循环执行 setTimeout(() => { if (this.status === "pending") { this.status = "rejected"; this.value = reason; if (this.rejectCallbackArr.length) this.rejectCallbackArr.forEach(item => item(this.value)); } }, 0) } // 执行执行器函数(包含异常捕获) try { excutorCallBack && excutorCallBack(resolveFn, rejectFn); } catch (error) { rejectFn(error) } } // 实例方法 then(resolveCallback, rejectCallback) { typeof resolveCallback !== "function" ? resolveCallback = result => result : null; typeof rejectCallback !== "function" ? rejectCallback = reason => {throw new Error(reason.message)} : null; return new MyPromise((resolve, reject) => { this.resolveCallbackArr.push(() => { try { let x = resolveCallback(this.value); x instanceof Promise ? x.then(resolve, reject) : resolve(x); }catch(err) { reject(err); } }) this.rejectCallbackArr.push(() => { try{ let x = rejectCallback(this.value); x instanceof Promise ? x.then(resolve, reject) : resolve(x); }catch(err) { reject(err); } }) }) } catch(rejectCallback) { return this.then(null, rejectCallback) }}export default MyPromise;