当前位置: 代码迷 >> 综合 >> Promise 仿写-原理解析
  详细解决方案

Promise 仿写-原理解析

热度:94   发布时间:2023-09-22 21:43:56.0
// 等待
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 = undefined;// 成功之后的值reason = undefined;// 成功之后的回调successCallback = [];// 失败之后的回调failCallback = [];resolve = value => {// 如果状态不是等待 阻止程序向下执行if (this.status !== PENGING) return;this.status = FULFILLED;this.value = 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 还是rejectresolvePromise(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;

 

  相关解决方案