ES6-手写Promise

首先Promise有三个状态 PENDING、FULFILLED、REJECTED ,只能由PENDING改变为FULFILLED、REJECTED,并且只能改变一次
Promise接收一个函数,这个函数有两个参数resolve方法和reject方法
resolve将PENDING改变为FULFILLED
reject将PENDING改变为FULFILLED

这里还实现了then,all,rece方法

class MyPromise{
      static PENDING = '待定';
      static FULFILLED = '成功';
      static REJECTED  = '失败';
      constructor(func){
          this.status =  MyPromise.PENDING;
          this.result = null;
          this.resolveCallback = [];
          this.rejectCallback = [];
          try {
              func(this.resolve.bind(this),this.reject.bind(this));
          } catch (error) {
              this.reject(error)
          }
          
      }
      resolve(result){
          setTimeout(() => {
              if(this.status == MyPromise.PENDING){
                  this.status = MyPromise.FULFILLED;
                  this.result   =  result;
                  this.resolveCallback.forEach(callback =>{
                      callback(result)
                  })
              }
          });
      }
      reject(result){
          setTimeout(() => {
              if(this.status == MyPromise.PENDING){
                  this.status = MyPromise.REJECTED;
                  this.result   =  result;
                  this.rejectCallback.forEach(callback =>{
                      callback(result)
                  })
              }
          });
      }
      then(onFULFILLED,onREJECTED){
          return new MyPromise( (resolve,reject)=>{
              onFULFILLED = typeof onFULFILLED  === 'function'?onFULFILLED:()=>{}
              onREJECTED = typeof onREJECTED  === 'function'?onREJECTED:()=>{}
              if(this.status == MyPromise.PENDING){
                  this.resolveCallback.push(onFULFILLED)
                  this.rejectCallback.push(onREJECTED)
              }
              if(this.status ==  MyPromise.FULFILLED){
              setTimeout(()=>{
                  onFULFILLED(this.result)
              })
              }
              if(this.status == MyPromise.REJECTED){
              setTimeout(()=>{
                  onREJECTED(this.result)
              })
              }
          })
      }
      all(arr){
          if(!Array.isArray(arr)){
              throw new Error('不是数组')
          }
          return new MyPromise( (resolve,reject) =>{
              let resolveValues = [];
              let num = 0;
              arr.forEach((item,index)=>{
                  item.then( result =>{
                      resolveValues[index] = result;
                      num ++;
                      if(resolveValues.length == arr.length){
                        return  resolve(resolveValues)
                      }
                  },(error)=>{
                      return  reject(error)
                  })
              })
          })
      }
      rece(arr){
          if(!Array.isArray(arr)){
              throw new Error('不是数组')
          }
          return new MyPromise( (resolve,reject) =>{
              arr.forEach((item,index)=>{
                  item.then( result =>{
                      return  resolve(result)
                  },(error)=>{
                      return  reject(error)
                  })
              })
          })
      }
  }
  console.log('第一步')
  let MyPromise =  new MyPromise((resolve,reject)=>{
      console.log('第二步')
      resolve('第一次');
      console.log('第四步')
  });

  MyPromise.all([com1(),com2()]).then(res =>{
      console.log(res)
  },(err)=>{
      console.log(err)
  })

  function com1(){
      return new MyPromise( (resolve,reject)=>{
          // throw new Error('宝错了')
          setTimeout( ()=>{
              resolve('com1')
          })
      })
  }

  function com2(){
      return new MyPromise( (resolve,reject)=>{
          setTimeout( ()=>{
              resolve('com2')
          })
      })
  }
  
  // MyPromise.then(
  //     result => console.log(result),
  //     result => console.log(result.messages)
  // ).then(
  //     result => console.log(result),
  //     result => console.log(result.messages)
  // )
        ```

  转载请注明: 小浩之随笔 ES6-手写Promise

 上一篇
状态管理工具Pinia 状态管理工具Pinia
介绍 Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案 Pinia 优势 1.抛弃了Mutations的操作,只有state、getters和actions.极大的简化了状态管理库的使用,让代
2022-03-05
下一篇 
TypeScript装饰器 TypeScript装饰器
什么是装饰器 装饰器是给一个方法,属性或类扩展一些新的行为,而不是去直接修改它本身的一个函数。 如果在项目中要使用装饰器,需要在 tsconfig.json 的编译配置中开启experimentalDecorators,将它设为 true。
2021-11-15
  目录