美文网首页
Promise的实现

Promise的实现

作者: 沉默紀哖呮肯伱酔 | 来源:发表于2020-06-10 09:42 被阅读0次
class Promise{
  construction(executor){
    this.status = "pending";
    this.resolveList = [];
    this.rejectList = [];
    
    const resolve = (args)=>{
        if(this.status !== "pending"){
          return
        }
        this.status = "fulfilled";
        while(this.resolveList.length){
          const callback = this.resolveList.shift();
          callback(args)
        }
    }

    const reject = (args) => {
        if(this.status !== "pending"){
          return
        }
        this.status = "rejected"
        while(this.resolveList.length){
          const callback = this.resolveList.shift();
          callback(args)
        }
    }

    executor(resolve,reject);
  }
  
  then(resolveCallback,rejectCallback){
    this.resolveList.push(resolveCallback);
    this.rejectList.push(rejectCallback);
  }

  // all promiseList列表中有一个失败 结果就为reject
  all(promiseList){
    const result = [];
    return new Promise((resolve,reject)=>{
      promiseList.map((item,i)=>{
        // Promise.resolve()用于处理传入值不为Promise的情况
        Promise.resolve(item).then((res)=>{
           result[i] = res;
           if(result.length === promiseList.length){
              resolve(result)
           }
        },(err)=>{
          reject(err)
        })
      })
    })
  }

  race(promiseList){
    return new Promise((resolve,reject)=>{
      promiseList.map((item,i)=>{
        // Promise.resolve()用于处理传入值不为Promise的情况
        Promise.resolve(item).then((res)=>{
          resolve(res)
        },(err)=>{
          reject(err)
        })
      })
    })
  }

}

相关文章

网友评论

      本文标题:Promise的实现

      本文链接:https://www.haomeiwen.com/subject/qyertktx.html