2021-12-22 今天手写一个低配版promise

基础 · 大致思路

Promise是通过构造函数实例化一个对象,然后通过实例对象上的then方法,来处理异步返回的结果。同时,promise / A+ 规范规定了:

promise 是一个拥有 then 方法的对象或函数,其行为符合本规范;
一个 Promise 的当前状态必须为以下三种状态中的一种:等待态(Pending)、执行态(Fulfilled)和拒绝态(Rejected)。

  • 每当new一个promise实例,都会传入一个我们自定义的executor方法,里面是一些异步操作(比如我们的后台请求),并立即调用
  • 调用时,会传入两个参数(resolve和reject方法),我们可以在异步的回调中使用这俩方法,传入我们获取到的回调值
  • 我们在resolve或reject中,会改变state状态,并且将传入的value或reason赋值给实例的this
  • 我们事先给构造函数的原型绑定了then方法,每当我们执行then时,会传入两个自定义的方法,并存到成功和失败的方法池中
  • 当我们的回调执行resolve或reject时,会在改变状态和value之后,顺便依次执行方法池中的自定义方法

简易 · promise垫片

 // 1. 定义state
      const PENDING = 'pending'
      const FULFILLED = 'fullfilled'
      const REJECTED = 'rejected'
      
 // 2. 定义构造函数
      function Promise (executor) {
        var _this = this
        this.state = PENDING
        this.value = undefined
        this.reason = undefined
        this.onFullfilled = []
        this.onRejected = []

        function resolve (value) {
          console.log(4);
          if(_this.state === PENDING) {
            _this.state = FULFILLED
            _this.value = value
            _this.onFullfilled.forEach(fn => fn(value))
          }
        }

        function reject (reason) {
          if(_this.state === PENDING) {
            _this.state = REJECTED
            _this.reason = reason
            _this.onRejected.forEach(fn => fn(reason))
          }
        }
        try {
          console.log(1);
          executor(resolve, reject)
        } catch(e) {
          reject(e)
        }
      }
      
// 3. 定义then方法
      Promise.prototype.then = function (onFullfilled, onRejected) {
        console.log(3);
        if(this.state === FULFILLED) {
          typeof onFullfilled === 'function' && onFullfilled(this.value)
        }
        if(this.state === REJECTED) {
          typeof onRejected === 'function' && onRejected(this.reason)
        }
        if(this.state === PENDING) {
          typeof onFullfilled === 'function' && this.onFullfilled.push(onFullfilled)
          typeof onRejected === 'function' && this.onRejected.push(onRejected)
        }
      }

使用:

      new Promise((resolve, reject) => {
        console.log(2);
        setTimeout(() => {
          resolve('成功了铁汁')
        }, 3000)
      }).then(res => {
        console.log(5);
      })

console顺序:
console顺序

难点 · 链式调用then

promise / A+ 规范规定了:

then 方法必须返回一个 promise 对象
promise2 = promise1.then(onFulfilled, onRejected);

鸣谢:https://zhuanlan.zhihu.com/p/144058361

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值