JS promise

时间:2020-10-06 19:53:44   收藏:0   阅读:36

Promise解释

Promise 是一个对象,它代表一个异步操作的最终完成或失败。由于它的 then 方法和 catch、finally 方法会返回一个新的 Promise,所以可以允许我们链式调用,解决了传统的回调地狱问题。

3个状态:pending、fullfilled、rejected。

new Promise((resolve,reject)=>{
  resolve()
}).then(res=>{

}).catch(err=>{

})

then和catch方法

finally方法

all及race方法

promise解决了什么问题

把异步操作的回调函数嵌套问题变成了异步操作的链式调用

实现一个简易的promise

class MyPromise{
  constructor(fn){
    this.status=‘pending‘;
    this.value=‘‘
    this.reason=‘‘
    //成功的回调
    this.onResolveCBs=[]
    //失败的回调
    this.onRejectCBs=[]

    let resolve=(reason)=>{
      if(this.status==‘pending‘){
        this.status=‘fulfilled‘;
        this.reason=reason;
        this.onResolveCBs.forEach(fn=>fn())
      }
    }

    let reject=(value)=>{
      if(this.status==‘pending‘){
        this.status=‘rejected‘
        this.value=value;
        this.onRejectCBs.forEach(fn=>fn())
      }
    }
    
    try{
      fn(resolve,reject);
    }catch(e){
      reject(e)
    }
  }

  then(onResolve,onReject){
    if(this.status===‘fulfilled‘){
      onResolve()
    }
    if(this.status===‘rejected‘){
      onReject();
    }
    if(this.status===‘pending‘){
      this.onResolveCBs.push(()=>onReject(this.value));
      this.onRejectCBs.push(()=>onReject(this.reason))
    }
  }
}


new MyPromise((resolve,reject)=>{
  setTimeout(()=>{
    resolve()
  },2000)
  // reject()
}).then(res=>{
  console.log(‘成功‘)
},err=>{
  console.log(‘失败‘)
})

参考

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!