自己写一个Promise A+ 发表于 2018-06-23 自己手动写一个Promise A+代码, 实现了基本功能(包括then/catch/all方法), 代码如下: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192class Promise { // constructor constructor(executorCallBack) { this.status = "pending"; this.value = undefined; this.fulfilledAry = []; this.rejectedAry = []; let resolveFn = result => { let timer = setTimeout(() => { clearTimeout(timer); if (!this.status === "pending") { return; } this.status = "fulfilled"; this.value = result; this.fulfilledAry.forEach(item => item(this.value)); }, 0); }; let rejectFn = reason => { let timer = setTimeout(() => { clearTimeout(timer); if (!this.status === "pending") { return; } this.status = "rejected"; this.value = reason; this.fulfilledAry.forEach(item => item(this.value)); }, 0); }; try { executorCallBack(resolveFn, rejectFn); } catch (err) { rejectFn(err); } } // methods then(fulfilledCallBack, rejectedCallBack) { typeof fulfilledCallBack !== "function" ? (fulfilledCallBack = result => result) : null; typeof rejectedCallBack !== "function" ? (rejectedCallBack = reason => { throw new Error(reason instanceof Error ? reason.message : reason); }) : null; return new Promise((resolve, reject) => { this.fulfilledAry.push(() => { try { let x = fulfilledCallBack(this.value); x instanceof Promise ? x.then(resolve, reject) : resolve(x); } catch (err) { reject(err); } }); this.rejectedAry.push(() => { try { let x = rejectedCallBack(this.value); x instanceof Promise ? x.then(resolve, reject) : resove(x); } catch (err) { reject(err); } }); }); } catch(rejectedCallBack) { return this.then(null, rejectedCallBack); } static all(promiseAry = []) { // 用Promise.all() 来执行 return new Promise((resolve, reject) => { let successCounter = 0, result = []; for (let i = 0; i < promiseAry.length; i++) { // promiseAry[i] 每一个处理的promise实例 promiseAry[i].then(val => { successCounter++; result[i] = val; if (successCounter === promiseAry.length) { resolve(result); } }, reject); } }); }}module.exports = Promise;