Based on syntax ES6 handwritten promise A + specification, the source
class Promise { constructor(excutorCallBack) { this.status = 'pending'; this.value = undefined; this.fulfilledAry = []; this.rejectedAry = []; //=>执行EXCUTOR(异常捕获) 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.rejectedAry.forEach(item => item(this.value)); }, 0 ); }; the try { excutorCallBack (resolveFn, rejectFn); } the catch (ERR) { // => information in the abnormal state processing REJECTED rejectFn (ERR); } } the then (fulfilledCallBack, rejectedCallBack) { // => process do not pass condition typeof ! fulfilledCallBack == 'function' fulfilledCallBack = Result => Result:? null ; typeof rejectedCallBack == 'function' rejectedCallBack reason = =>!? { the throw new new Error (reason the instanceof Error? reason.message : reason); } : null; //=>返回一个新的PROMISE实例 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) : resolve(x); } catch (err) { reject(err); } }); }); } catch(rejectedCallBack) { return this.then(null, rejectedCallBack); } static all(promiseAry = []) {//=>Promise.all() return newPromise ((Resolve, Reject) => { // => the INDEX: Record Number of successful RESULT: The result of a successful recording the let index = 0 , Result = []; for (the let I = 0; I <promiseAry.length; I ++ ) { // => promiseAry [I]: // the PROMISE each instance to be processed promiseAry [I] .then (Val => { index ++ ; Result [I] = Val; // => index needs and promiseAry the correspondence, and the sequence order of the array to ensure consistent results IF (index === promiseAry.length) { Resolve (result); } }, reject); } }); } } module.exports = Promise;