• 【JavaScript】过了一年,懒癌患者终于整理了一下『手写Promise A+』


    手写前的准备工作:

    如果感觉对 Promise 还不太熟悉的就先移步 Promise 入门,及 JS执行机制及Event Loop

    Promise A+规范:目前我们使用的 Promise 是基于 Promise A+ 规范实现,借助 promises-aplus-tests 来检测我们的代码是否符合规范。

    一、Promise 核心逻辑实现

    我们先简单实现一下 Promise 的基础功能。先看原生 Promise 实现:

    const promise = new Promise((resolve, reject) => {
       resolve('success')
       reject('err')
    })
    
    promise.then(value => {
      console.log('resolve', value)
    }, reason => {
      console.log('reject', reason)
    })
    
    // 输出 resolve success
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    我们来分析一下基本原理

    1. Promise 是一个类,在执行这个类的时候会传入一个执行器,这个执行器会立即执行
    2. Promise 会有三种状态
      • Pending 等待
      • Fulfilled 完成
      • Rejected 失败
    3. 状态只能由 Pending --> Fulfilled 或者 Pending --> Rejected,且一但发生改变便不可二次修改;
    4. Promise 中使用 resolve 和 reject 两个函数来更改状态;
    5. then 方法内部做但事情就是状态判断
      • 如果状态是成功,调用成功回调函数
      • 如果状态是失败,调用失败回调函数

    逻辑实现如下

    // MyPromise.js
    
    // 状态控制常量
    const PENDING = 'pending';
    const FULFILLED = 'fulfilled';
    const REJECTED = 'rejected';
    
    class MyPromise {
      constructor(executor){
        // executor 是一个执行器,进入会立即执行
        // 并传入resolve和reject方法
        executor(this.resolve, this.reject)
      }
    
      // 储存状态的变量,初始值是 pending
      status = PENDING;
    
      // resolve和reject为什么要用箭头函数?
      // 如果直接调用的话,普通函数this指向的是window或者undefined
      // 用箭头函数就可以让this指向当前实例对象
      // 成功之后的值
      value = null;
      // 失败之后的原因
      reason = null;
    
      // 更改成功后的状态
      resolve = (value) => {
        // 只有状态是等待,才执行状态修改
        if (this.status === PENDING) {
          // 状态修改为成功
          this.status = FULFILLED;
          // 保存成功之后的值
          this.value = value;
        }
      }
    
      // 更改失败后的状态
      reject = (reason) => {
        // 只有状态是等待,才执行状态修改
        if (this.status === PENDING) {
          // 状态成功为失败
          this.status = REJECTED;
          // 保存失败后的原因
          this.reason = reason;
        }
      }
    
      then(onFulfilled, onRejected) {
        // 判断状态
        if (this.status === FULFILLED) {
          // 调用成功回调,并且把值返回
          onFulfilled(this.value);
        } else if (this.status === REJECTED) {
          // 调用失败回调,并且把原因返回
          onRejected(this.reason);
        }
      }
    }
    
    module.exports = MyPromise
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    基于当前逻辑,测试一下,是否能达到预期:

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
       resolve('success')
       reject('err')
    })
    
    promise.then(value => {
      console.log('resolve', value)
    }, reason => {
      console.log('reject', reason)
    })
    
    // 执行结果:resolve success
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    执行结果符合我们的预期,第一步完成了👏👏👏

    二、在 Promise 类中加入异步逻辑

    上面还没有经过异步处理,如果有异步逻辑加如来会带来一些问题,例如:

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
      setTimeout(() => {
        resolve('success')
      }, 2000); 
    })
    
    promise.then(value => {
      console.log('resolve', value)
    }, reason => {
      console.log('reject', reason)
    })
    
    // 没有打印信息!!!
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    分析原因

    主线程代码立即执行,setTimeout 是异步代码,then 会马上执行,这个时候判断 Promise 状态,状态是 Pending,然而之前并没有判断等待这个状态

    这里就需要我们处理一下 Pending 状态,我们改造一下之前的代码 🤔

    1. 缓存成功与失败回调

    // MyPromise.js
    
    // MyPromise 类中新增
    // 存储成功回调函数
    onFulfilledCallback = null;
    // 存储失败回调函数
    onRejectedCallback = null;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2. then 方法中的 Pending 的处理

    // MyPromise.js
    then(onFulfilled, onRejected) {
      // 判断状态
      if (this.status === FULFILLED) {
        // 调用成功回调,并且把值返回
        onFulfilled(this.value);
      } else if (this.status === REJECTED) {
        // 调用失败回调,并且把原因返回
        onRejected(this.reason);
      } else if (this.status === PENDING) {
        // ==== 新增 ====
        // 因为不知道后面状态的变化情况,所以将成功回调和失败回调存储起来
        // 等到执行成功失败函数的时候再传递
        this.onFulfilledCallback = onFulfilled;
        this.onRejectedCallback = onRejected;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3. resolve 与 reject 中调用回调函数

    // MyPromise.js
    
    // 更改成功后的状态
    resolve = (value) => {
      // 只有状态是等待,才执行状态修改
      if (this.status === PENDING) {
        // 状态修改为成功
        this.status = FULFILLED;
        // 保存成功之后的值
        this.value = value;
        // ==== 新增 ====
        // 判断成功回调是否存在,如果存在就调用
        this.onFulfilledCallback && this.onFulfilledCallback(value);
      }
    }
    // MyPromise.js
    // 更改失败后的状态
    reject = (reason) => {
      // 只有状态是等待,才执行状态修改
      if (this.status === PENDING) {
        // 状态成功为失败
        this.status = REJECTED;
        // 保存失败后的原因
        this.reason = reason;
        // ==== 新增 ====
        // 判断失败回调是否存在,如果存在就调用
        this.onRejectedCallback && this.onRejectedCallback(reason)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    我们再执行一下上面测试用例

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
      setTimeout(() => {
        resolve('success')
      }, 2000); 
    })
    
    promise.then(value => {
      console.log('resolve', value)
    }, reason => {
      console.log('reject', reason)
    })
    
    // 等待 2s 输出 resolve success
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    目前已经可以简单处理异步问题。

    三、实现 then 方法多次调用添加多个处理函数

    Promise 的 then 方法是可以被多次调用的。这里如果有三个 then 的调用,如果是同步回调,那么直接返回当前的值就行;如果是异步回调,那么保存的成功失败的回调,需要用不同的值保存,因为都互不相同。之前的代码需要改进。

    同样的先看一个示例

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
      setTimeout(() => {
        resolve('success')
      }, 2000); 
    })
    
    promise.then(value => {
      console.log(1)
      console.log('resolve', value)
    })
     
    promise.then(value => {
      console.log(2)
      console.log('resolve', value)
    })
    
    promise.then(value => {
      console.log(3)
      console.log('resolve', value)
    })
    
    // 3
    // resolve success
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    目前的代码只能输出:3 resolve success,这是因为回调函数多次更新替换,出现1、2 丢失。

    因此,可以回调保存历次回调为数组进行保存,保证所有 then 中的回调函数都可以执行。

    1. MyPromise 类中新增两个数组

    // MyPromise.js
    
    // 存储成功回调函数
    // onFulfilledCallback = null;
    onFulfilledCallbacks = [];
    // 存储失败回调函数
    // onRejectedCallback = null;
    onRejectedCallbacks = [];
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2. 回调函数存入数组中

    // MyPromise.js
    then(onFulfilled, onRejected) {
      // 判断状态
      if (this.status === FULFILLED) {
        // 调用成功回调,并且把值返回
        onFulfilled(this.value);
      } else if (this.status === REJECTED) {
        // 调用失败回调,并且把原因返回
        onRejected(this.reason);
      } else if (this.status === PENDING) {
        // ==== 新增 ====
        // 因为不知道后面状态的变化,这里先将成功回调和失败回调存储起来
        // 等待后续调用
        this.onFulfilledCallbacks.push(onFulfilled);
        this.onRejectedCallbacks.push(onRejected);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3. 循环调用成功和失败回调

    // MyPromise.js
    
    // 更改成功后的状态
    resolve = (value) => {
      // 只有状态是等待,才执行状态修改
      if (this.status === PENDING) {
        // 状态修改为成功
        this.status = FULFILLED;
        // 保存成功之后的值
        this.value = value;
        // ==== 新增 ====
        // resolve里面将所有成功的回调拿出来执行
        while (this.onFulfilledCallbacks.length) {
          // Array.shift() 取出数组第一个元素,然后()调用,shift不是纯函数,取出后,数组将失去该元素,直到数组为空
          this.onFulfilledCallbacks.shift()(value)
        }
      }
    }
    
    // 更改失败后的状态
    reject = (reason) => {
      // 只有状态是等待,才执行状态修改
      if (this.status === PENDING) {
        // 状态成功为失败
        this.status = REJECTED;
        // 保存失败后的原因
        this.reason = reason;
        // ==== 新增 ====
        // resolve里面将所有失败的回调拿出来执行
        while (this.onRejectedCallbacks.length) {
          this.onRejectedCallbacks.shift()(reason)
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    再来运行一下,看看结果

    1
    resolve success
    2
    resolve success
    3
    resolve success
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    👏👏👏 完美,继续

    四、实现 then 方法的链式调用

    then 方法要链式调用那么就需要返回一个 Promise 对象
    then 方法里面 return 一个返回值作为下一个 then 方法的参数,如果是 return 一个 Promise 对象,那么就需要判断它的状态

    举个栗子

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
      // 目前这里只处理同步的问题
      resolve('success')
    })
    
    function other () {
      return new MyPromise((resolve, reject) =>{
        resolve('other')
      })
    }
    promise.then(value => {
      console.log(1)
      console.log('resolve', value)
      return other()
    }).then(value => {
      console.log(2)
      console.log('resolve', value)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    用目前的手写代码运行的时候会报错 无法链式调用

    }).then(value => {
      ^
    
    TypeError: Cannot read property 'then' of undefined
    
    • 1
    • 2
    • 3
    • 4

    接着改

    // MyPromise.js
    
    class MyPromise {
      ......
      then(onFulfilled, onRejected) {
        // ==== 新增 ====
        // 为了链式调用这里直接创建一个 MyPromise,并在后面 return 出去
        const promise2 = new MyPromise((resolve, reject) => {
          // 这里的内容在执行器中,会立即执行
          if (this.status === FULFILLED) {
            // 获取成功回调函数的执行结果
            const x = onFulfilled(this.value);
            // 传入 resolvePromise 集中处理
            resolvePromise(x, resolve, reject);
          } else if (this.status === REJECTED) {
            onRejected(this.reason);
          } else if (this.status === PENDING) {
            this.onFulfilledCallbacks.push(onFulfilled);
            this.onRejectedCallbacks.push(onRejected);
          }
        }) 
        
        return promise2;
      }
    }
    
    function resolvePromise(x, resolve, reject) {
      // 判断x是不是 MyPromise 实例对象
      if(x instanceof MyPromise) {
        // 执行 x,调用 then 方法,目的是将其状态变为 fulfilled 或者 rejected
        // x.then(value => resolve(value), reason => reject(reason))
        // 简化之后
        x.then(resolve, reject)
      } else{
        // 普通值
        resolve(x)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    执行一下,结果

    1
    resolve success
    2
    resolve other
    
    • 1
    • 2
    • 3
    • 4

    em… 符合预期

    五、then 方法链式调用识别 Promise 是否返回自己

    如果 then 方法返回的是自己的 Promise 对象,则会发生循环调用,这个时候程序会报错

    例如下面这种情况

    // test.js
    
    const promise = new Promise((resolve, reject) => {
      resolve(100)
    })
    const p1 = promise.then(value => {
      console.log(value)
      return p1
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用原生 Promise 执行这个代码,会报类型错误

    100
    Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>
    
    • 1
    • 2

    我们在 MyPromise 实现一下

    // MyPromise.js
    
    class MyPromise {
      ......
      then(onFulfilled, onRejected) {
        const promise2 = new MyPromise((resolve, reject) => {
          if (this.status === FULFILLED) {
            const x = onFulfilled(this.value);
            // resolvePromise 集中处理,将 promise2 传入
            resolvePromise(promise2, x, resolve, reject);
          } else if (this.status === REJECTED) {
            onRejected(this.reason);
          } else if (this.status === PENDING) {
            this.onFulfilledCallbacks.push(onFulfilled);
            this.onRejectedCallbacks.push(onRejected);
          }
        }) 
        
        return promise2;
      }
    }
    
    function resolvePromise(promise2, x, resolve, reject) {
      // 如果相等了,说明return的是自己,抛出类型错误并返回
      if (promise2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #'))
      }
      if(x instanceof MyPromise) {
        x.then(resolve, reject)
      } else{
        resolve(x)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    执行一下,竟然报错了!!!

            resolvePromise(promise2, x, resolve, reject);
                           ^
    
    ReferenceError: Cannot access 'promise2' before initialization
    
    • 1
    • 2
    • 3
    • 4

    为啥会报错呢?从错误提示可以看出,我们必须要等 promise2 完成初始化。这个时候我们就要用上宏微任务和事件循环的知识了,这里就需要创建一个异步函数去等待 promise2 完成初始化,这里选择 queueMicrotask创建异步微任务。

    // MyPromise.js
    
    class MyPromise {
      ......
      then(onFulfilled, onRejected) {
        const promise2 = new MyPromise((resolve, reject) => {
          if (this.status === FULFILLED) {
            // ==== 新增 ====
            // 创建一个微任务等待 promise2 完成初始化
            queueMicrotask(() => {
              // 获取成功回调函数的执行结果
              const x = onFulfilled(this.value);
              // 传入 resolvePromise 集中处理
              resolvePromise(promise2, x, resolve, reject);
            })  
          } else if (this.status === REJECTED) {
          ......
        }) 
        
        return promise2;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    执行一下

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
        resolve('success')
    })
     
    // 这个时候将promise定义一个p1,然后返回的时候返回p1这个promise
    const p1 = promise.then(value => {
       console.log(1)
       console.log('resolve', value)
       return p1
    })
     
    // 运行的时候会走reject
    p1.then(value => {
      console.log(2)
      console.log('resolve', value)
    }, reason => {
      console.log(3)
      console.log(reason.message)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    这里得到我们的结果

    1
    resolve success
    3
    Chaining cycle detected for promise #<Promise>
    
    • 1
    • 2
    • 3
    • 4

    哈哈,搞定 开始下一步

    六、捕获错误及 then 链式调用其他状态代码补充

    目前还缺少重要的一个环节,就是我们的错误捕获还没有处理

    1. 捕获执行器错误

    捕获执行器中的代码,如果执行器中有代码错误,那么 Promise 的状态要变为失败

    // MyPromise.js
    
    constructor(executor){
      // ==== 新增 ====
      // executor 是一个执行器,进入会立即执行
      // 并传入resolve和reject方法
      try {
        executor(this.resolve, this.reject)
      } catch (error) {
        // 如果有错误,就直接执行 reject
        this.reject(error)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    验证一下:

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
        // resolve('success')
        throw new Error('执行器错误')
    })
     
    promise.then(value => {
      console.log(1)
      console.log('resolve', value)
    }, reason => {
      console.log(2)
      console.log(reason.message)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    执行结果

    2
    执行器错误
    
    • 1
    • 2

    OK,通过

    2. then 执行的时错误捕获

    // MyPromise.js
    
    then(onFulfilled, onRejected) {
      // 为了链式调用这里直接创建一个 MyPromise,并在后面 return 出去
      const promise2 = new MyPromise((resolve, reject) => {
        // 判断状态
        if (this.status === FULFILLED) {
          // 创建一个微任务等待 promise2 完成初始化
          queueMicrotask(() => {
            // ==== 新增 ====
            try {
              // 获取成功回调函数的执行结果
              const x = onFulfilled(this.value);
              // 传入 resolvePromise 集中处理
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            }  
          })  
        } else if (this.status === REJECTED) {
          // 调用失败回调,并且把原因返回
          onRejected(this.reason);
        } else if (this.status === PENDING) {
          // 等待
          // 因为不知道后面状态的变化情况,所以将成功回调和失败回调存储起来
          // 等到执行成功失败函数的时候再传递
          this.onFulfilledCallbacks.push(onFulfilled);
          this.onRejectedCallbacks.push(onRejected);
        }
      }) 
      
      return promise2;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    验证一下:

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
        resolve('success')
        // throw new Error('执行器错误')
     })
     
    // 第一个then方法中的错误要在第二个then方法中捕获到
    promise.then(value => {
      console.log(1)
      console.log('resolve', value)
      throw new Error('then error')
    }, reason => {
      console.log(2)
      console.log(reason.message)
    }).then(value => {
      console.log(3)
      console.log(value);
    }, reason => {
      console.log(4)
      console.log(reason.message)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    执行结果 👇

    1
    resolve success
    4
    then error
    
    • 1
    • 2
    • 3
    • 4

    这里成功打印了1中抛出的错误 then error

    七、参考 fulfilled 状态下的处理方式,对 rejected 和 pending 状态进行改造

    改造内容包括:

    1. 增加异步状态下的链式调用
    2. 增加回调函数执行结果的判断
    3. 增加识别 Promise 是否返回自己
    4. 增加错误捕获
    // MyPromise.js
    
    then(onFulfilled, onRejected) {
      // 为了链式调用这里直接创建一个 MyPromise,并在后面 return 出去
      const promise2 = new MyPromise((resolve, reject) => {
        // 判断状态
        if (this.status === FULFILLED) {
          // 创建一个微任务等待 promise2 完成初始化
          queueMicrotask(() => {
            try {
              // 获取成功回调函数的执行结果
              const x = onFulfilled(this.value);
              // 传入 resolvePromise 集中处理
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            } 
          })  
        } else if (this.status === REJECTED) { 
          // ==== 新增 ====
          // 创建一个微任务等待 promise2 完成初始化
          queueMicrotask(() => {
            try {
              // 调用失败回调,并且把原因返回
              const x = onRejected(this.reason);
              // 传入 resolvePromise 集中处理
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error)
            } 
          }) 
        } else if (this.status === PENDING) {
          // 等待
          // 因为不知道后面状态的变化情况,所以将成功回调和失败回调存储起来
          // 等到执行成功失败函数的时候再传递
          this.onFulfilledCallbacks.push(() => {
            // ==== 新增 ====
            queueMicrotask(() => {
              try {
                // 获取成功回调函数的执行结果
                const x = onFulfilled(this.value);
                // 传入 resolvePromise 集中处理
                resolvePromise(promise2, x, resolve, reject);
              } catch (error) {
                reject(error)
              } 
            }) 
          });
          this.onRejectedCallbacks.push(() => {
            // ==== 新增 ====
            queueMicrotask(() => {
              try {
                // 调用失败回调,并且把原因返回
                const x = onRejected(this.reason);
                // 传入 resolvePromise 集中处理
                resolvePromise(promise2, x, resolve, reject);
              } catch (error) {
                reject(error)
              } 
            }) 
          });
        }
      }) 
      
      return promise2;
    }
    复制代码
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    八、then 中的参数变为可选

    上面我们处理 then 方法的时候都是默认传入 onFulfilled、onRejected 两个回调函数,但是实际上原生 Promise 是可以选择参数的单传或者不传,都不会影响执行。

    例如下面这种 👇

    // test.js
    
    const promise = new Promise((resolve, reject) => {
      resolve(100)
    })
    
    promise
      .then()
      .then()
      .then()
      .then(value => console.log(value))
    
    // 输出 100
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    所以我们需要对 then 方法做一点小小的调整

    // MyPromise.js
    
    then(onFulfilled, onRejected) {
      // 如果不传,就使用默认函数
      onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
      onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason};
    
      // 为了链式调用这里直接创建一个 MyPromise,并在后面 return 出去
      const promise2 = new MyPromise((resolve, reject) => {
      ......
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    改造完自然是需要验证一下的

    先看情况一:resolve 之后

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
      resolve('succ')
    })
     
    promise.then().then().then(value => console.log(value))
    
    // 打印 succ
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    先看情况一:reject 之后

    // test.js
    
    const MyPromise = require('./MyPromise')
    const promise = new MyPromise((resolve, reject) => {
      reject('err')
    })
     
    promise.then().then().then(value => console.log(value), reason => console.log(reason))
    
    // 打印 err
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    写到这里,麻雀版的 Promise 基本完成了,鼓掌 👏👏👏

    九、测试

    到这里手写工作就基本完成了,前面主要为了方便理解,所以有一些冗余代码,我规整一下

    // MyPromise.js
    
    // 先定义三个常量表示状态
    const PENDING = 'pending';
    const FULFILLED = 'fulfilled';
    const REJECTED = 'rejected';
    
    // 新建 MyPromise 类
    class MyPromise {
      constructor(executor){
        // executor 是一个执行器,进入会立即执行
        // 并传入resolve和reject方法
        try {
          executor(this.resolve, this.reject)
        } catch (error) {
          this.reject(error)
        }
      }
    
      // 储存状态的变量,初始值是 pending
      status = PENDING;
      // 成功之后的值
      value = null;
      // 失败之后的原因
      reason = null;
    
      // 存储成功回调函数
      onFulfilledCallbacks = [];
      // 存储失败回调函数
      onRejectedCallbacks = [];
    
      // 更改成功后的状态
      resolve = (value) => {
        // 只有状态是等待,才执行状态修改
        if (this.status === PENDING) {
          // 状态修改为成功
          this.status = FULFILLED;
          // 保存成功之后的值
          this.value = value;
          // resolve里面将所有成功的回调拿出来执行
          while (this.onFulfilledCallbacks.length) {
            // Array.shift() 取出数组第一个元素,然后()调用,shift不是纯函数,取出后,数组将失去该元素,直到数组为空
            this.onFulfilledCallbacks.shift()(value)
          }
        }
      }
    
      // 更改失败后的状态
      reject = (reason) => {
        // 只有状态是等待,才执行状态修改
        if (this.status === PENDING) {
          // 状态成功为失败
          this.status = REJECTED;
          // 保存失败后的原因
          this.reason = reason;
          // resolve里面将所有失败的回调拿出来执行
          while (this.onRejectedCallbacks.length) {
            this.onRejectedCallbacks.shift()(reason)
          }
        }
      }
    
      then(onFulfilled, onRejected) {
        const realOnFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
        const realOnRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason};
    
        // 为了链式调用这里直接创建一个 MyPromise,并在后面 return 出去
        const promise2 = new MyPromise((resolve, reject) => {
          const fulfilledMicrotask = () =>  {
            // 创建一个微任务等待 promise2 完成初始化
            queueMicrotask(() => {
              try {
                // 获取成功回调函数的执行结果
                const x = realOnFulfilled(this.value);
                // 传入 resolvePromise 集中处理
                resolvePromise(promise2, x, resolve, reject);
              } catch (error) {
                reject(error)
              } 
            })  
          }
    
          const rejectedMicrotask = () => { 
            // 创建一个微任务等待 promise2 完成初始化
            queueMicrotask(() => {
              try {
                // 调用失败回调,并且把原因返回
                const x = realOnRejected(this.reason);
                // 传入 resolvePromise 集中处理
                resolvePromise(promise2, x, resolve, reject);
              } catch (error) {
                reject(error)
              } 
            }) 
          }
          // 判断状态
          if (this.status === FULFILLED) {
            fulfilledMicrotask() 
          } else if (this.status === REJECTED) { 
            rejectedMicrotask()
          } else if (this.status === PENDING) {
            // 等待
            // 因为不知道后面状态的变化情况,所以将成功回调和失败回调存储起来
            // 等到执行成功失败函数的时候再传递
            this.onFulfilledCallbacks.push(fulfilledMicrotask);
            this.onRejectedCallbacks.push(rejectedMicrotask);
          }
        }) 
        
        return promise2;
      }
    
      // resolve 静态方法
      static resolve (parameter) {
        // 如果传入 MyPromise 就直接返回
        if (parameter instanceof MyPromise) {
          return parameter;
        }
    
        // 转成常规方式
        return new MyPromise(resolve =>  {
          resolve(parameter);
        });
      }
    
      // reject 静态方法
      static reject (reason) {
        return new MyPromise((resolve, reject) => {
          reject(reason);
        });
      }
    }
    
    function resolvePromise(promise2, x, resolve, reject) {
      // 如果相等了,说明return的是自己,抛出类型错误并返回
      if (promise2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #'))
      }
      // 判断x是不是 MyPromise 实例对象
      if(x instanceof MyPromise) {
        // 执行 x,调用 then 方法,目的是将其状态变为 fulfilled 或者 rejected
        // x.then(value => resolve(value), reason => reject(reason))
        // 简化之后
        x.then(resolve, reject)
      } else{
        // 普通值
        resolve(x)
      }
    }
    
    module.exports = MyPromise;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151

    到这一步手写部分基本大功告成 🎉🎉🎉

    Promise A+ 测试

    1. 安装一下 promises-aplus-tests
    npm install promises-aplus-tests -D
    
    • 1
    2. 手写代码中加入 deferred
    // MyPromise.js
    
    MyPromise {
      ......
    }
    
    MyPromise.deferred = function () {
      var result = {};
      result.promise = new MyPromise(function (resolve, reject) {
        result.resolve = resolve;
        result.reject = reject;
      });
    
      return result;
    }
    module.exports = MyPromise;
    复制代码
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    3. 配置启动命令
    {
      "name": "promise",
      "version": "1.0.0",
      "description": "my promise",
      "main": "MyPromise.js",
      "scripts": {
        "test": "promises-aplus-tests MyPromise"
      },
      "author": "ITEM",
      "license": "ISC",
      "devDependencies": {
        "promises-aplus-tests": "^2.1.2"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    开启测试

    npm run test
    
    • 1

    虽然功能上没啥问题,但是测试却失败了。

    针对提示信息,我翻看了一下 Promise A+ 规范,发现我们应该是在 2.3.x 上出现了问题,这里规范使用了不同的方式进行了 then 的返回值判断。

    在这里插入图片描述

    红框的细节,我们都没有处理,这里要求判断 x 是否为 object 或者 function,满足则接着判断 x.then 是否存在,这里可以理解为判断 x 是否为 promise,这里都功能实际与我们手写版本中 x instanceof MyPromise 功能相似。

    我们还是按照规范改造一下 resolvePromise 方法吧

    // MyPromise.js
    
    function resolvePromise(promise, x, resolve, reject) {
      // 如果相等了,说明return的是自己,抛出类型错误并返回
      if (promise === x) {
        return reject(new TypeError('The promise and the return value are the same'));
      }
    
      if (typeof x === 'object' || typeof x === 'function') {
        // x 为 null 直接返回,走后面的逻辑会报错
        if (x === null) {
          return resolve(x);
        }
    
        let then;
        try {
          // 把 x.then 赋值给 then 
          then = x.then;
        } catch (error) {
          // 如果取 x.then 的值时抛出错误 error ,则以 error 为据因拒绝 promise
          return reject(error);
        }
    
        // 如果 then 是函数
        if (typeof then === 'function') {
          let called = false;
          try {
            then.call(
              x, // this 指向 x
              // 如果 resolvePromise 以值 y 为参数被调用,则运行 [[Resolve]](promise, y)
              y => {
                // 如果 resolvePromise 和 rejectPromise 均被调用,
                // 或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用
                // 实现这条需要前面加一个变量 called
                if (called) return;
                called = true;
                resolvePromise(promise, y, resolve, reject);
              },
              // 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
              r => {
                if (called) return;
                called = true;
                reject(r);
              });
          } catch (error) {
            // 如果调用 then 方法抛出了异常 error:
            // 如果 resolvePromise 或 rejectPromise 已经被调用,直接返回
            if (called) return;
    
            // 否则以 error 为据因拒绝 promise
            reject(error);
          }
        } else {
          // 如果 then 不是函数,以 x 为参数执行 promise
          resolve(x);
        }
      } else {
        // 如果 x 不为对象或者函数,以 x 为参数执行 promise
        resolve(x);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    改造后启动测试

    在这里插入图片描述

    完美通过 !!!!!!

  • 相关阅读:
    docker笔记(一):安装、常用命令
    day34 集合总结
    linux常用操作命令中带/和不带的区别
    数据分析的概念
    算法设计(一) : 搜索算法实现八皇后问题
    RocketMQ安装部署
    Spring Security整合企业微信的扫码登录,企微的API震惊到我了
    ssh 免密登陆
    AI推介-大语言模型LLMs论文速览(arXiv方向):2024.01.01-2024.01.10
    数据结构-线性表
  • 原文地址:https://blog.csdn.net/qq_38987146/article/details/126228981