Promise A+ 封装练习

Promise A+ 规范封装练习,显示了then,catch,all和then链

封装自己的Promise

// ES6 CLASS 构造类
class Promise {
  //  constructor 指向的就是函数本身私有, 外面使用时,就直接new Promise() 创建实例  
  //  创建实例的时候,我们就把实例中传入的方法执行,所以excutorCallBack 进来就执行
  constructor(excutorCallBack) {

    // primise 进来就是pending状态,,,成功时fulfilled,失败时rejected
    this.status = 'pending'
    this.value = null;
    // 用于存入then方法传入进来的方法
    this.fulfilledAry = [];
    this.rejectedAry = [];
    //2、 执行excutorCallBack  成功或者失败只能执行一个,所以根据状态来进行控制
    let resolveFn = (resolve) => {
      let timer = setTimeout(() => {
        clearTimeout(timer)
        // 判断只有pending状态才可以进入
        if (this.status !== 'pending') return
        this.status = 'fulfilled';
        this.value = resolve;
        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)
    }

    //1、 处理异常
    try {
      excutorCallBack(resolveFn, rejectFn)
    } catch (err) {
      rejectFn(err)
    }


  }
  // 原型方法写在constructor外面
  then(fulfilledCallBack, rejectedCallBack) {
    typeof fulfilledCallBack !== 'function' ? fulfilledCallBack = () => {
      return this.value
    } : null;
    typeof rejectedCallBack !== 'function' ? rejectedCallBack = () => {
      throw new Error(this.value)
    } : null;
    // 实现then链式写法
    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)
        }

      })
    })
    // // 这里使用了发布订阅模式
    // this.fulfilledAry.push(fulfilledCallBack);
    // this.rejectedAry.push(rejectedCallBack)
  }
  catch(rejectedCallBack) {
    return this.then(null, rejectedCallBack)
  }

  //=>STATIC ALL
  static all(promiseAry) {
    return new Promise((resolve, reject) => {
      let resultAry = [],
        index = 0;
      for (let i = 0; i < promiseAry.length; i++) {
        promiseAry[i].then(result => {
          index++;
          resultAry[i] = result;
          if (index === promiseAry.length) {
            resolve(resultAry);
          }
        }).catch(reason => {
          reject(reason);
        });
      }
    });
  }
}

module.exports = Promise
项目中使用自己的Promise
let Promise = require('./Promise');


// PROMISE A+ 规范练习
new Promise((resolve, reject) => {

  console.log(1)
  // throw new Error('NO')
  setTimeout(() => {
    resolve(100)
    console.log(2)
  }, 0)

}).then(res => {
  console.log(res)
  console.log(4)
}).catch(reson=>{
  console.log(reson)
})
console.log(6)

// 结果:1,6,2,100,4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值