js|Promise 仿写-原理解析

// 等待 const PENGING = 'pending'; // 成功 const FULFILLED = 'fulfilled'; // 失败 const REJECTED = 'rejected'; class MyPromise { constructor(excutor) { try { excutor(this.resolve, this.reject); } catch (error) { this.reject(error) } } // promise 状态 status = PENGING; // 失败之后的值 value = https://www.it610.com/article/undefined; // 成功之后的值 reason = undefined; // 成功之后的回调 successCallback = []; // 失败之后的回调 failCallback = []; resolve = value => { // 如果状态不是等待 阻止程序向下执行 if (this.status !== PENGING) return; this.status = FULFILLED; this.value = https://www.it610.com/article/value; // 判断成功回调是否存在 如果存在 调用 while (this.successCallback.length) this.successCallback.shift()(); } reject = reason => { if (this.status !== PENGING) return; // 将状态改为失败 this.status = REJECTED; this.reason = reason; // 判断失败回调 是否存在 存在即回调 this.failCallback && this.failCallback(this.reason); // 删除回调事件中的首个 while (this.failCallback.length) this.failCallback.shift()(); } then(successCallback, failCallback) { // 参数可选 successCallback = successCallback ? successCallback : value => value; // 参数可选 failCallback = failCallback ? failCallback : reason => { throw reason }; let promise2 = new MyPromise((resolve, reject) => { // 判断 状态 if (this.status === FULFILLED) { setTimeout(() => { try { let x = successCallback(this.value); //判断x 的值 是普通值 还是promise 对象 // 如果 是普通值 直接resolve // 如果是promise 对象 查看promise 返回的结果 // 再根据 promise 对象返回的结果 决定调用resolve 还是reject resolvePromise(promise2, x, resolve, reject); } catch (error) { console.log(error); } }, 0) } else if (this.status === REJECTED) { setTimeout(() => { try { let x = failCallback(this.reason); } catch (error) { resolvePromise(promise2, x, resolve, reject); } }, 0) } else { // 等待 // 将成功回调和失败回调存储起来 this.successCallback.push(() => { setTimeout(() => { try { let x = successCallback(this.value) } catch (error) { resolvePromise(promise2, x, resolve, reject) } }, 0) }) } }); return promise2; } finally(callback) { return this.then(value => { return MyPromise.resolve(callback()).then(() => value) }, reason => { return MyPromise.resolve(callback()).then(() => { throw reason; }) }) } catch(failCallback) { return this.then(undefined, failCallback) } static all(array) { let result = []; let index = 0; return new MyPromise((resolve, reject) => { function addData(key, value) { result[key] = value; index++; if (index === array.length) { resolve(resolve); } } for (let i = 0; i < array.length; i++) { let current = array[i]; if (current instanceof MyPromise) { current.then(value => addData(i, value), reason => reject(reason)) } else { addData(i,array[i]); } } }) } static resolve(value){ if(value instanceof MyPromise){ return value; } return new MyPromise(resolve => resolve(value)); } } function resolvePromise(promise2, resolve,reject) { if(promise2 ===x){ return reject(new TypeError('chaining cycle deletede for promise')); } if(x instanceof MyPromise){ x.then(resolve,reject); }else{ resolve(x); } } module.exports =MyPromise;

【js|Promise 仿写-原理解析】

    推荐阅读