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 = 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 还是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;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值