JavaScript中Promise使用、原理以及实现过程

开发 前端
本篇文章不在于实现一个完整的 promise,但是通过对 promise 的尝试实现,已经对 promise 有了更加深入的了解,这样的实现过程可以帮助开发者在开发过程中更好的使用 promise 。

1.什么是 Promise

promise 是目前 JS 异步编程的主流解决方案,遵循 Promises/A+ 方案。

2.Promise 原理简析

(1)promise 本身相当于一个状态机,拥有三种状态:

  •  pending
  •  fulfilled
  •  rejected

一个 promise 对象初始化时的状态是 pending,调用了 resolve 后会将 promise 的状态扭转为 fulfilled,调用 reject 后会将 promise 的状态扭转为 rejected,这两种扭转一旦发生便不能再扭转该 promise 到其他状态。

(2)promise 对象原型上有一个 then 方法,then 方法会返回一个新的 promise 对象,并且将回调函数 return 的结果作为该 promise resolve 的结果,then 方法会在一个 promise 状态被扭转为 fulfilled 或 rejected 时被调用。then 方法的参数为两个函数,分别为 promise 对象的状态被扭转为 fulfilled 和 rejected 对应的回调函数。

3.Promise 如何使用

构造一个 promise 对象,并将要执行的异步函数传入到 promise 的参数中执行,并且在异步执行结束后调用 resolve( ) 函数,就可以在 promise 的 then 方法中获取到异步函数的执行结果:

  1. new Promise((resolve, reject) => {  
  2.   setTimeout(() => {  
  3.     resolve()  
  4.   }, 1000)  
  5. }).then(  
  6.   res => {},  
  7.   err => {}  

同时在 Promise 还为我们实现了很多方便使用的方法:

  •  Promise.resolve

Promise.resolve 返回一个 fulfilled 状态的 promise。

  1. const a = Promise.resolve(1)  
  2. a.then(  
  3.   res => {  
  4.     // res = 1  
  5.   },  
  6.   err => {}  
  •  Promise.all

Promise.all 接收一个 promise 对象数组作为参数,只有全部的 promise 都已经变为 fulfilled 状态后才会继续后面的处理。Promise.all 本身返回的也是一个 promise 。

  1. const promise1 = new Promise((resolve, reject) => {  
  2.   setTimeout(() => {  
  3.     resolve('promise1')  
  4.   }, 100)  
  5. })  
  6. const promise2 = new Promise((resolve, reject) => {  
  7.   setTimeout(() => {  
  8.     resolve('promise2')  
  9.   }, 100)  
  10. })  
  11. const promises = [promise1, promise2]  
  12. Promise.all(promises).then(  
  13.   res => {  
  14.     // promises 全部变为 fulfilled 状态的处理  
  15.   },  
  16.   err => {  
  17.     // promises 中有一个变为 rejected 状态的处理  
  18.   }  
  •  Promise.race

Promise.race 和 Promise.all 类似,只不过这个函数会在 promises 中第一个 promise 的状态扭转后就开始后面的处理(fulfilled、rejected 均可) 。

  1. const promise1 = new Promise((resolve, reject) => {  
  2.   setTimeout(() => {  
  3.     resolve('promise1')  
  4.   }, 100)  
  5. })  
  6. const promise2 = new Promise((resolve, reject) => {  
  7.   setTimeout(() => {  
  8.     resolve('promise2')  
  9.   }, 1000)  
  10. })  
  11. const promises = [promise1, promise2]  
  12. Promise.race(promises).then(  
  13.   res => {  
  14.     // 此时只有 promise1 resolve 了,promise2 仍处于 pending 状态  
  15.   },  
  16.   err => {}  

配合 async await 使用

现在的开发场景中我们大多会用 async await 语法糖来等待一个 promise 的执行结果,使代码的可读性更高。async 本身是一个语法糖,将函数的返回值包在一个 promise 中返回。 

  1. // async 函数会返回一个 promise  
  2. const p = async function f() {  
  3.   return 'hello world'  
  4.  
  5. p.then(res => console.log(res)) // hello world 

开发技巧

在前端开发上 promise 大多被用来请求接口,Axios 库也是开发中使用最频繁的库,但是频繁的 try catch 扑捉错误会让代码嵌套很严重。考虑如下代码的优化方式。

  1. const getUserInfo = async function() {  
  2.   return new Promise((resolve, reject) => {  
  3.     // resolve() || reject()  
  4.   })  
  5.  
  6. // 为了处理可能的抛错,不得不将 try catch 套在代码外边,一旦嵌套变多,代码可读性就会急剧下降  
  7. try {  
  8.   const user = await getUserInfo()  
  9. } catch (e) {} 

好的处理方法是在异步函数中就将错误 catch,然后正常返回,如下所示 👇 

  1. const getUserInfo = async function() {  
  2.   return new Promise((resolve, reject) => {  
  3.     // resolve() || reject()  
  4.   }).then(  
  5.     res => {  
  6.       return [res, null] // 处理成功的返回结果  
  7.     },  
  8.     err => {  
  9.       return [null, err] // 处理失败的返回结果  
  10.     }  
  11.   )  
  12.  
  13. const [user, err] = await getUserInfo()  
  14. if (err) {  
  15.   // err 处理  
  16.  
  17. // 这样的处理是不是清晰了很多呢 

4.Promise 源码实现

知识的学习需要知其然且知其所以然,所以通过一点点实现的一个 promise 能够对 promise 有着更深刻的理解。

(1)首先按照最基本的 promise 调用方式实现一个简单的 promise (基于 ES6 规范编写),假设我们有如下调用方式:

  1. new Promise((resolve, reject) => {  
  2.   setTimeout(() => {  
  3.     resolve(1)  
  4.   }, 1000)  
  5. })  
  6.   .then(  
  7.     res => {  
  8.       console.log(res)  
  9.       return 2  
  10.     },  
  11.     err => {}  
  12.   )  
  13.   .then(  
  14.     res => {  
  15.       console.log(res)  
  16.     },  
  17.     err => {}  
  18.   ) 

我们首先要实现一个 Promise 的类,这个类的构造函数会传入一个函数作为参数,并且向该函数传入 resolve 和 reject 两个方法。

初始化 Promise 的状态为 pending。 

  1. class MyPromise {  
  2.   constructor(executor) {  
  3.     this.executor = executor  
  4.     this.value = null  
  5.     this.status = 'pending'  
  6.     const resolve = value => {  
  7.       if (this.status === 'pending') {  
  8.         this.value = value          // 调用 resolve 后记录 resolve 的值  
  9.         this.status = 'fulfilled'   // 调用 resolve 扭转 promise 状态  
  10.       }  
  11.     }  
  12.     const reject = value => {  
  13.       if (this.status === 'pending') {  
  14.         this.value = value          // 调用 reject 后记录 reject 的值  
  15.         this.status = 'rejected'    // 调用 reject 扭转 promise 状态  
  16.       }  
  17.     }  
  18.     this.executor(resolve, reject)  
  19.   } 

(2)接下来要实现 promise 对象上的 then 方法,then 方法会传入两个函数作为参数,分别作为 promise 对象 resolve 和 reject 的处理函数。

这里要注意三点:

  •  then 函数需要返回一个新的 promise 对象
  •  执行 then 函数的时候这个 promise 的状态可能还没有被扭转为 fulfilled 或 rejected
  •  一个 promise 对象可以同时多次调用 then 函数 
  1. class MyPromise {  
  2.   constructor(executor) {  
  3.     this.executor = executor  
  4.     this.value = null  
  5.     this.status = 'pending'  
  6.     this.onFulfilledFunctions = [] // 存放这个 promise 注册的 then 函数中传的第一个函数参数  
  7.     this.onRejectedFunctions = [] // 存放这个 promise 注册的 then 函数中传的第二个函数参数  
  8.     const resolve = value => {  
  9.       if (this.status === 'pending') {  
  10.         this.value = value  
  11.         this.status = 'fulfilled'  
  12.         this.onFulfilledFunctions.forEach(onFulfilled => {  
  13.           onFulfilled() // 将 onFulfilledFunctions 中的函数拿出来执行  
  14.         })  
  15.       }  
  16.     }  
  17.     const reject = value => {  
  18.       if (this.status === 'pending') {  
  19.         this.value = value  
  20.         this.status = 'rejected'  
  21.         this.onRejectedFunctions.forEach(onRejected => {  
  22.           onRejected() // 将 onRejectedFunctions 中的函数拿出来执行  
  23.         })  
  24.       }  
  25.     }  
  26.     this.executor(resolve, reject)  
  27.   }  
  28.   then(onFulfilled, onRejected) {  
  29.     const self = this  
  30.     if (this.status === 'pending') {  
  31.       /**  
  32.        *  当 promise 的状态仍然处于 ‘pending’ 状态时,需要将注册 onFulfilled、onRejected 方法放到 promise 的 onFulfilledFunctions、onRejectedFunctions 备用  
  33.        */  
  34.       return new MyPromise((resolve, reject) => {  
  35.         this.onFulfilledFunctions.push(() => {  
  36.           const thenReturn = onFulfilled(self.value)  
  37.           resolve(thenReturn)  
  38.         })  
  39.         this.onRejectedFunctions.push(() => {  
  40.           const thenReturn = onRejected(self.value)  
  41.           resolve(thenReturn)  
  42.         })  
  43.       })  
  44.     } else if (this.status === 'fulfilled') {  
  45.       return new MyPromise((resolve, reject) => {  
  46.         const thenReturn = onFulfilled(self.value)  
  47.         resolve(thenReturn)  
  48.       })  
  49.     } else { 
  50.        return new MyPromise((resolve, reject) => {  
  51.         const thenReturn = onRejected(self.value)  
  52.         resolve(thenReturn)  
  53.       })  
  54.     }  
  55.   }  

对于以上完成的 MyPromise 进行测试,测试代码如下:

  1. const p = new MyPromise((resolve, reject) => {  
  2.   setTimeout(() => {  
  3.     resolve(1)  
  4.   }, 1000)  
  5. })  
  6. p.then(res => {  
  7.   console.log('first then', res)  
  8.   return res + 1  
  9. }).then(res => {  
  10.   console.log('first then', res)  
  11. })  
  12. p.then(res => {  
  13.   console.log(`second then`, res)  
  14.   return res + 1  
  15. }).then(res => {  
  16.   console.log(`second then`, res)  
  17. })  
  18. /**  
  19.  *  输出结果如下:  
  20.  *  first then 1  
  21.  *  first then 2  
  22.  *  second then 1  
  23.  *  second then 2  
  24.  */ 

(3)在 promise 相关的内容中,有一点常常被我们忽略,当 then 函数中返回的是一个 promise 应该如何处理?

考虑如下代码: 

  1. // 使用正确的 Promise  
  2. new Promise((resolve, reject) => {  
  3.   setTimeout(() => {  
  4.     resolve()  
  5.   }, 1000)  
  6. })  
  7.   .then(res => {  
  8.     console.log('外部 promise')  
  9.     return new Promise((resolve, reject) => {  
  10.       resolve(`内部 promise`)  
  11.     })  
  12.   })  
  13.   .then(res => {  
  14.     console.log(res)  
  15.   })  
  16. /**  
  17.  * 输出结果如下:  
  18.  * 外部 promise  
  19.  * 内部 promise  
  20.  */ 

通过以上的输出结果不难判断,当 then 函数返回的是一个 promise 时,promise 并不会直接将这个 promise 传递到下一个 then 函数,而是会等待该 promise resolve 后,将其 resolve 的值,传递给下一个 then 函数,找到我们实现的代码的 then 函数部分,做以下修改: 

  1. then(onFulfilled, onRejected) {  
  2.     const self = this  
  3.     if (this.status === 'pending') {  
  4.         return new MyPromise((resolve, reject) => {  
  5.         this.onFulfilledFunctions.push(() => {  
  6.             const thenReturn = onFulfilled(self.value)  
  7.             if (thenReturn instanceof MyPromise) { 
  8.                  // 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态  
  9.                 thenReturn.then(resolve, reject)  
  10.             } else {  
  11.                 resolve(thenReturn)  
  12.             }  
  13.         })  
  14.         this.onRejectedFunctions.push(() => {  
  15.             const thenReturn = onRejected(self.value)  
  16.             if (thenReturn instanceof MyPromise) {  
  17.                 // 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态  
  18.                 thenReturn.then(resolve, reject)  
  19.             } else {  
  20.                 resolve(thenReturn)  
  21.             }  
  22.         })  
  23.         })  
  24.     } else if (this.status === 'fulfilled') {  
  25.         return new MyPromise((resolve, reject) => {  
  26.             const thenReturn = onFulfilled(self.value)  
  27.             if (thenReturn instanceof MyPromise) {  
  28.                 // 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态  
  29.                 thenReturn.then(resolve, reject)  
  30.             } else {  
  31.                 resolve(thenReturn)  
  32.             }  
  33.         })  
  34.     } else {  
  35.         return new MyPromise((resolve, reject) => {  
  36.             const thenReturn = onRejected(self.value)  
  37.             if (thenReturn instanceof MyPromise) {  
  38.                 // 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态  
  39.                 thenReturn.then(resolve, reject)  
  40.             } else {  
  41.                 resolve(thenReturn)  
  42.             }  
  43.         })  
  44.     }  

(4) 之前的 promise 实现代码仍然缺少很多细节逻辑,下面会提供一个相对完整的版本,注释部分是增加的代码,并提供了解释。 

  1. class MyPromise {  
  2.   constructor(executor) {  
  3.     this.executor = executor  
  4.     this.value = null  
  5.     this.status = 'pending'  
  6.     this.onFulfilledFunctions = []  
  7.     this.onRejectedFunctions = []  
  8.     const resolve = value => {  
  9.       if (this.status === 'pending') {  
  10.         this.value = value  
  11.         this.status = 'fulfilled'  
  12.         this.onFulfilledFunctions.forEach(onFulfilled => {  
  13.           onFulfilled()  
  14.         })  
  15.       }  
  16.     }  
  17.     const reject = value => {  
  18.       if (this.status === 'pending') {  
  19.         this.value = value  
  20.         this.status = 'rejected'  
  21.         this.onRejectedFunctions.forEach(onRejected => {  
  22.           onRejected()  
  23.         })  
  24.       }  
  25.     }  
  26.     this.executor(resolve, reject)  
  27.   }  
  28.   then(onFulfilled, onRejected) {  
  29.     const self = this  
  30.     if (typeof onFulfilled !== 'function') {  
  31.       // 兼容 onFulfilled 未传函数的情况  
  32.       onFulfilled = function() {}  
  33.     }  
  34.     if (typeof onRejected !== 'function') {  
  35.       // 兼容 onRejected 未传函数的情况  
  36.       onRejected = function() {}  
  37.     }  
  38.     if (this.status === 'pending') {  
  39.       return new MyPromise((resolve, reject) => {  
  40.         this.onFulfilledFunctions.push(() => {  
  41.           try {  
  42.             const thenReturn = onFulfilled(self.value)  
  43.             if (thenReturn instanceof MyPromise) {  
  44.               thenReturn.then(resolve, reject)  
  45.             } else {  
  46.               resolve(thenReturn)  
  47.             }  
  48.           } catch (err) {  
  49.             // catch 执行过程的错误  
  50.             reject(err)  
  51.           }  
  52.         })  
  53.         this.onRejectedFunctions.push(() => {  
  54.           try {  
  55.             const thenReturn = onRejected(self.value)  
  56.             if (thenReturn instanceof MyPromise) {  
  57.               thenReturn.then(resolve, reject)  
  58.             } else {  
  59.               resolve(thenReturn)  
  60.             }  
  61.           } catch (err) {  
  62.             // catch 执行过程的错误  
  63.             reject(err)  
  64.           }  
  65.         })  
  66.       })  
  67.     } else if (this.status === 'fulfilled') {  
  68.       return new MyPromise((resolve, reject) => {  
  69.         try {  
  70.           const thenReturn = onFulfilled(self.value)  
  71.           if (thenReturn instanceof MyPromise) {  
  72.             thenReturn.then(resolve, reject)  
  73.           } else {  
  74.             resolve(thenReturn)  
  75.           }  
  76.         } catch (err) {  
  77.           // catch 执行过程的错误  
  78.           reject(err)  
  79.         }  
  80.       })  
  81.     } else {  
  82.       return new MyPromise((resolve, reject) => {  
  83.         try {  
  84.           const thenReturn = onRejected(self.value)  
  85.           if (thenReturn instanceof MyPromise) {  
  86.             thenReturn.then(resolve, reject)  
  87.           } else {  
  88.             resolve(thenReturn)  
  89.           }  
  90.         } catch (err) {  
  91.           // catch 执行过程的错误  
  92.           reject(err)  
  93.         }  
  94.       })  
  95.     }  
  96.   } 
  97.  

(5)至此一个相对完整的 promise 已经实现,但他仍有一些问题,了解宏任务、微任务的同学一定知道,promise 的 then 函数实际上是注册一个微任务,then 函数中的参数函数并不会同步执行。

查看如下代码: 

  1. new Promise((resolve,reject)=> 
  2.     console.log(`promise 内部`)  
  3.     resolve()  
  4. }).then((res)=> 
  5.     console.log(`第一个 then`)  
  6. })  
  7. console.log(`promise 外部`)  
  8. /**  
  9.  * 输出结果如下:  
  10.  * promise 内部  
  11.  * promise 外部  
  12.  * 第一个 then  
  13.  */  
  14. // 但是如果使用我们写的 MyPromise 来执行上面的程序  
  15. new MyPromise((resolve,reject)=> 
  16.     console.log(`promise 内部`)  
  17.     resolve()  
  18. }).then((res)=> 
  19.     console.log(`第一个 then`)  
  20. })  
  21. console.log(`promise 外部`)  
  22. /**  
  23.  * 输出结果如下:  
  24.  * promise 内部  
  25.  * 第一个 then  
  26.  * promise 外部  
  27.  */ 

以上的原因是因为的我们的 then 中的 onFulfilled、onRejected 是同步执行的,当执行到 then 函数时上一个 promise 的状态已经扭转为 fulfilled 的话就会立即执行 onFulfilled、onRejected。

要解决这个问题也非常简单,将 onFulfilled、onRejected 的执行放在下一个事件循环中就可以了。 

  1. if (this.status === 'fulfilled') {  
  2.   return new MyPromise((resolve, reject) => {  
  3.     setTimeout(() => {  
  4.       try {  
  5.         const thenReturn = onFulfilled(self.value)  
  6.         if (thenReturn instanceof MyPromise) {  
  7.           thenReturn.then(resolve, reject)  
  8.         } else {  
  9.           resolve(thenReturn)  
  10.         }  
  11.       } catch (err) {  
  12.         // catch 执行过程的错误  
  13.         reject(err)  
  14.       }  
  15.     })  
  16.   }, 0)  

关于宏任务和微任务的解释,我曾在掘金上看到过一篇非常棒的文章,它用银行柜台的例子解释了为什么会同时存在宏任务和微任务两个队列,文章链接贴到文末感兴趣的可以看一下。

5.Promise/A+ 方案解读 

我们上面实现的一切逻辑,均是按照 Promise/A+ 规范实现的,Promise/A+ 规范说的大部分内容已经在上面 promise 的实现过程中一一讲解。接下来讲述相当于一个汇总:

      1.  promise 有三个状态 pending、fulfilled、rejected,只能由 pending 向 fulfilled 、rejected 两种状态发生改变。

      2.  promise 需要提供一个 then 方法,then 方法接收 (onFulfilled,onRejected) 两个函数作为参数。

      3.  onFulfilled、onRejected 须在 promise 完成后后(状态扭转)后调用,且只能调用一次。

      4.  onFulfilled、onRejected 仅仅作为函数进行调用,不能够将 this 指向调用它的 promise。

      5.  onFulfilled、onRejected 必须在执行上下文栈只包含平台代码后才能执行。平台代码指 引擎,环境,Promise 实现代码。(PS:这处规范要求 onFulfilled、onRejected 函数的执行必须在 then 被调用的那个事件循环之后的事件循环。但是规范并没有要求是把它们作为一个微任务或是宏任务去执行,只是各平台的实现均把 Promise 的 onFulfilled、onRejected 放到微任务队列中去执行了)。

      6.  onFulfilled、onRejected 必须是个函数,否则忽略。

      7.  then 方法可以被一个 promise 多次调用。

      8.  then 方法需要返回一个 promise。

      9.  Promise 的解析过程是一个抽象操作,将 Promise 和一个值作为输入,我们将其表示为 [[Resolve]](promise,x), [[Resolve]](promise,x) 是创建一个 Resolve 方法并传入 promise,x(promise 成功时返回的值) 两个参数,如果 x 是一个 thenable 对象(含有 then 方法),并且假设 x 的行为类似 promise, [[Resolve]](promise,x) 会创造一个采用 x 状态的 promise,否则 [[Resolve]](promise,x) 会用 x 来扭转 promise 的状态。取得输入的不同的 promise 实现方式可以进行交互,只要它们都暴露了 Promise/A+ 兼容方法即可。它也允许 promise 使用合理的 then 方法同化一些不合规范的 promise 实现。

第 9 点只看文档比较晦涩难懂,其实它是针对我们的 then 方法中的这行代码做的规范解释。 

  1. return new MyPromise((resolve, reject) => {  
  2.   try {  
  3.     const thenReturn = onFulfilled(self.value)  
  4.     if (thenReturn instanceof MyPromise) {  
  5.       // 👈 就是这一行代码  
  6.       thenReturn.then(resolve, reject)  
  7.     } else {  
  8.       resolve(thenReturn)  
  9.     }  
  10.   } catch (err) {  
  11.     reject(err)  
  12.   }  
  13. }) 

因为 Promise 并不是 JS 一开始就有的标准,是被很多第三方独立实现的一个方法,所以无法通过 instanceof 来判断返回值是否是一个 promise 对象,所以为了使不同的 promise 可以交互,才有了我上面提到的第 9 条规范。当返回值 thenReturn 是一个 promise 对象时,我们需要等待这个 promise 的状态发生扭转并用它的返回值来 resolve 外层的 promise。

所以最后我们还需要实现 [[Resolve]](promise,x),来满足 promise 规范,规范如下所示。

 

  1. /**  
  2.  * resolvePromise 函数即为根据 x 的值来决定 promise2 的状态的函数  
  3.  * @param {Promise} promise2  then 函数需要返回的 promise 对象  
  4.  * @param {any} x onResolve || onReject 执行后得到的返回值  
  5.  * @param {Function} resolve  MyPromise 中的 resolve 方法  
  6.  * @param {Function} reject  MyPromise 中的 reject 方法  
  7.  */  
  8. function resolvePromise(promise2, x, resolve, reject) {  
  9.   if (promise2 === x) {  
  10.     // 2.3.1 promise2 和 x 指向同一个对象  
  11.     reject(new TypeError())  
  12.     return  
  13.   }  
  14.   if (x instanceof MyPromise) {  
  15.     // 2.3.2 x 是一个 MyPromise 的实例,采用他的状态  
  16.     if (x.status === 'pending') {  
  17.       x.then(  
  18.         value => {  
  19.           resolvePromise(promise2, value, resolve, reject)  
  20.         },  
  21.         err => {  
  22.           reject(err)  
  23.         }  
  24.       )  
  25.     } else {  
  26.       x.then(resolve, reject)  
  27.     }  
  28.     return  
  29.   }  
  30.   if (x && (typeof x === 'function' || typeof x === 'object')) {  
  31.     // 2.3.3 x 是一个对象或函数  
  32.     try {  
  33.       const then = x.then // 2.3.3.1 声明 变量 then = x.then  
  34.       let promiseStatusConfirmed = false // promise 的状态确定  
  35.       if (typeof then === 'function') {  
  36.         // 2.3.3.3 then 是一个方法,把 x 绑定到 then 函数中的 this 上并调用  
  37.         then.call(  
  38.           x,  
  39.           value => {  
  40.             // 2.3.3.3.1 then 函数返回了值 value,则使用 [[Resolve]](promise, value),用于监测 value 是不是也是一个 thenable 的对象  
  41.             if (promiseStatusConfirmed) return // 2.3.3.3.3 即这三处谁选执行就以谁的结果为准  
  42.             promiseStatusConfirmed = true  
  43.             resolvePromise(promise2, value, resolve, reject)  
  44.             return  
  45.           },  
  46.           err => {  
  47.             // 2.3.3.3.2  then 函数抛错 err ,用 err reject 当前的 promise  
  48.             if (promiseStatusConfirmed) return // 2.3.3.3.3 即这三处谁选执行就以谁的结果为准  
  49.             promiseStatusConfirmed = true  
  50.             reject(err)  
  51.             return  
  52.           }  
  53.         )  
  54.       } else {  
  55.         // 2.3.3.4  then 不是一个方法,则用 x 扭转 promise 状态 为 fulfilled  
  56.         resolve(x)  
  57.       }  
  58.     } catch (e) {  
  59.       // 2.3.3.2 在取得 x.then 的结果时抛出错误 e 的话,使用 e reject 当前的 promise  
  60.       if (promiseStatusConfirmed) return // 2.3.3.3.3 即这三处谁选执行就以谁的结果为准 
  61.        promiseStatusConfirmed = true  
  62.       reject(e)  
  63.       return  
  64.     }  
  65.   } else {  
  66.     resolve(x) // 2.3.4 如果 x 不是 object || function,用 x 扭转 promise 状态 为 fulfilled  
  67.   }  

然后我们就可以用 resolcePromise 方法替换之前的这部分代码。 

  1. return new MyPromise((resolve, reject) => {  
  2.   try {  
  3.     const thenReturn = onFulfilled(self.value)  
  4.     if (thenReturn instanceof MyPromise) {  
  5.       thenReturn.then(resolve, reject)  
  6.     } else {  
  7.       resolve(thenReturn)  
  8.     }  
  9.   } catch (err) {  
  10.     reject(err)  
  11.   }  
  12. })  
  13. // 变成下面这样 👇   
  14. return new MyPromise((resolve, reject) => {  
  15.   try {  
  16.     const thenReturn = onFulfilled(self.value)  
  17.     resolvePromise(resolve,reject)  
  18.   } catch (err) {  
  19.     reject(err)  
  20.   }  
  21. }) 

本篇文章不在于实现一个完整的 promise,但是通过对 promise 的尝试实现,已经对 promise 有了更加深入的了解,这样的实现过程可以帮助开发者在开发过程中更好的使用 promise 。 

 

责任编辑:庞桂玉 来源: 中国开源
相关推荐

2017-05-11 20:20:59

JavascriptPromiseWeb

2015-07-23 11:59:27

JavascriptPromise

2023-09-15 15:31:23

异步编程Promise

2014-05-16 10:04:19

JavaScriptthis原理

2023-10-04 07:25:59

JavaScriptpromises

2021-08-10 09:57:27

JavaScriptPromise 前端

2017-10-26 21:08:15

Tomcat可插拔SCI

2021-09-02 12:07:48

Swift 监听系统Promise

2023-03-01 10:37:51

2021-06-07 09:44:10

JavaScript开发代码

2020-02-14 13:50:32

JavaScript前端技术

2022-07-11 20:46:39

AQSJava

2020-12-15 08:01:24

Promise参数ES6

2015-03-10 13:55:31

JavaScript预解析原理及实现

2009-09-07 05:24:22

C#窗体继承

2021-06-06 19:51:07

JavaScript异步编程

2012-05-09 11:34:48

JavaScriptMotion Dete

2021-06-30 10:32:33

反射多态Java

2022-10-11 23:50:43

JavaScript编程Promise

2021-03-09 07:37:42

技术Promise测试
点赞
收藏

51CTO技术栈公众号