首页 > 语言 > JavaScript > 正文

如何利用ES6进行Promise封装总结

2024-05-06 15:42:31
字体:
来源:转载
供稿:网友

原生Promise解析

简介

promise是异步编程的一种解决方案,比传统的解决方案--回调函数和事件--更合理和强大。

promise简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果,从语法上来说,Promise是一个对象,从它可以获取异步操作的消息,Promise提供统一的API,各种异步操作都可以用同样的方法进行处理

特点

对象的状态不受外界影响,Promise对象代表一个异步操作,有三种状态:Pendding、fulfilled、rejected。只有异步操作的结果,可以决定当前是哪一种状态,其他操作都无法改变这个状态。

一旦状态改变,就不会在变,任何时候都可以得到这个结果,只有两种可能:从Pendding变为fulfilled和从Pendding变为rejected。只要这两种情况发生,状态就凝固了,会一直保持这个结果,这时就称为resolved。

利用es6进行Promise封装

处理同步任务

原生方法调用方式

  new Promise((resolve,reject)=>{    resolve(1)  }).then(res=>{    console.log(res) //1  })

同步封装思考

1.由调用方式可见Promise是一个类
2.它接收一个回调函数,这个回调函数接受resolve和reject方法作为参数
3.当状态改变后执行then方法,并将resolve或reject的结果作为then方法接受回调函数的参数

  class Mypromise{    constructor(callback){      this.status='pendding'      //成功结果      this.s_res = null      // 失败结果      this.f_res = null      callback((arg)=>{ // 使用箭头函数this不会丢失       // 改变状态为成功       this.status = 'fulfilled'       this.s_res = arg      },(arg)=>{        // 改变状态为失败        this.status = 'rejected'        this.f_res = arg       })    }    then(onresolve,onreject){      if(this.status === 'fulfilled'){ // 当状态为成功时        onresolve(this.s_res)      }else if(this.status === 'rejected'){ // 当状态为失败时        onreject(this.f_res)      }    }  }

处理异步任务

原生调用方式

  new Promise((resolve,reject)=>{    setTimeOut(()=>{      resolve(1)    },1000)  }).then(res=>{    console.log(res)  })

异步封装思考

1.根据js执行机制,setTimeOut属于宏任务,then回调函数属于微任务,当主线程执行完成后,会从异步队列中取出本次的微任务先执行。

2.也就是说,then方法执行时,状态还没有改变,所有我们需要将then方法执行的回调保存起来,等到异步代码执行完成后,在统一执行then方法的回调函数

  class Mypromise{    constructor(callback){      this.status='pendding'      //成功结果      this.s_res = null      // 失败结果      this.f_res = null      this.query = [] // ++       callback((arg)=>{ // 使用箭头函数this不会丢失       // 改变状态为成功       this.status = 'fulfilled'       this.s_res = arg       // 当状态改变后,统一执行then方法的回调       this.query.forEach(item=>{         item.resolve(arg)       })      },(arg)=>{        // 改变状态为失败        this.status = 'rejected'        this.f_res = arg         // 当状态改变后,统一执行then方法的回调       this.query.forEach(item=>{         item.reject(arg)       })      })    }    then(onresolve,onreject){      if(this.status === 'fulfilled'){ // 当状态为成功时        onresolve(this.s_res)      }else if(this.status === 'rejected'){ // 当状态为失败时        onreject(this.f_res)      }else{ // ++ 状态没有改变        this.query.push({ // 保存回调函数到队列中          resolve:onresolve,          reject:onreject        })      }    }  }             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选