手写Promise 实现 then catch方法(新添加resolve,reject,all)
class MyPromise { constructor(callback) { if (typeof callback !== 'function') throw new TypeError(`MyPromise resolver ${callback} is not a function`); this.state = 'pending'; //定义状态 this.result = void 0; // 保存结果 this.callbackArr = []; // 保存异步任务函数 const resolve = val => { if (this.state !== 'pending') return; this.state = 'fulfilled'; this.result = val; this.callbackArr.forEach(item => { item.resolvedFn(this.result); }); }; const reject = reason => { if (this.state !== 'pending') return; this.state = 'rejected'; this.result = reason; this.callbackArr.forEach(item => { item.rejectedFn(this.result); }); }; // 错误处理 try { callback(resolve, reject); } catch (error) { reject(error); } } then(resolvedFn, rejectedFn) { if (typeof resolvedFn !== 'function') { resolvedFn = val => val; } if (typeof rejectedFn !== 'function') { rejectedFn = () => { throw this.result; }; } return new MyPromise((resolve, reject) => { const callback = fn => { try { const returnVal = fn(this.result); if (returnVal instanceof MyPromise) { returnVal.then( val => { resolve(val); }, reason => { reject(reason); } ); } else { resolve(returnVal); } } catch (error) { reject(error); } }; if (this.state === 'fulfilled') { // queueMicrotask开启微任务 queueMicrotask(() => { callback(resolvedFn); }); } else if (this.state === 'rejected') { queueMicrotask(() => { callback(rejectedFn); }); } else if (this.state === 'pending') { this.callbackArr.push({ resolvedFn: () => { queueMicrotask(() => { callback(resolvedFn); }); }, rejectedFn: () => { queueMicrotask(() => { callback(rejectedFn); }); }, }); } }); } catch(rejectedFn) { return this.then(val => val, rejectedFn); } static resolve(arg) { if (arg instanceof MyPromise) { return arg; } return new MyPromise(resolve => { resolve(arg); }); } static reject(arg) { if (arg instanceof MyPromise) { return arg; } return new MyPromise((_, reject) => { reject(arg); }); } static all(arr) { if (!Array.isArray(arr)) throw new TypeError('argument is not a Array'); return new MyPromise((resolve, reject) => { const reslutArr = []; arr.forEach((item, index) => { if (!(item instanceof MyPromise)) { item = MyPromise.resolve(item); } item.then( val => { reslutArr[index] = val; if (index == arr.length - 1) { resolve(reslutArr); } }, reason => { reject(reason); } ); }); }); } }
posted on 2022-10-26 16:19 _^_^_nicole 阅读(48) 评论(0) 收藏 举报
浙公网安备 33010602011771号