翼度科技»论坛 编程开发 JavaScript 查看内容

手写Promise方法(实现Promise A+规范)

11

主题

11

帖子

33

积分

新手上路

Rank: 1

积分
33
目录

手写Promise

Promise 构造函数

我们先来写 Promise 的构造函数。需要处理的事件如下:

  • Promise 状态记录:this.state
  • 记录成功或失败的值:this.value和this.reason
  • 收集解决和拒绝回调函数:this.resolveCallbacks和this.rejectCallbacks
  • 执行首次传入的解决和拒绝回调函数:func(this.resolve, this.reject)
  1. class myPromise {
  2.     constructor(func) {
  3.         this.state = 'pending' // Promise状态
  4.         this.value = undefined // 成功的值
  5.         this.reason = undefined // 失败的值
  6.         this.resolveCallbacks = [] // 收集解决回调函数
  7.         this.rejectCallbacks = [] // 收集拒绝回调函数
  8.         try { // 对传入的函数进行try...catch...做容错处理
  9.             func(this.resolve, this.reject) // 执行首次传入的两个回调函数
  10.         } catch (e) {
  11.             this.reject(e)
  12.         }
  13.     }
  14. }
复制代码
三个状态(pending、rejected和fulfilled)

pending:待定状态。待定Promise。只有在then方法执行后才会保持此状态。
fulfilled:解决状态。终止Promise。只有在resolve方法执行后才会由pending更改为此状态。
rejected:拒绝状态。终止Promise。只有在reject方法执行后才会由pending更改为此状态。
注意:其中只有pedding状态可以变更为rejected或fulfilled。rejected或fulfilled不能更改其他任何状态。
三个方法(resolve、reject和then)

resolve方法实现要点


  • 状态由pending为fulfilled。
  • resolve方法传入的value参数赋值给this.value
  • 按顺序执行resolveCallbacks里面所有解决回调函数
  • 利用call方法将解决回调函数内部的this绑定为undefined
坑点 1:resolve方法内部this指向会丢失,进而造成this.value丢失。
解决办法:我们将resolve方法定义为箭头函数。在构造函数执行后,箭头函数可以绑定实例对象的this指向。
  1. // 2.1. Promise 状态
  2. resolve = (value) => { // 在执行构造函数时内部的this通过箭头函数绑定实例对象
  3.     if (this.state === 'pending') {
  4.         this.state = 'fulfilled' // 第一点
  5.         this.value = value // 第二点
  6.         while (this.resolveCallbacks.length > 0) { // 第三点
  7.             this.resolveCallbacks.shift().call(undefined) // 第四点
  8.         }
  9.     }
  10. }
复制代码
reject方法实现要点


  • 状态由pending为rejected
  • reject方法传入的reason参数赋值给this.reason
  • 按顺序执行rejectCallbacks里面所有拒绝回调函数
  • 利用call方法将拒绝回调函数内部的this绑定为undefined
坑点 1: reject 方法内部this指向会丢失,进而造成this.reason丢失。
解决办法:我们将reject方法定义为箭头函数。在构造函数执行后,箭头函数可以绑定实例对象的this指向。
  1. // 2.1. Promise 状态
  2. reject = (reason) => { // 在执行构造函数时内部的this通过箭头函数绑定实例对象
  3.     if (this.state === 'pending') {
  4.         this.state = 'rejected' // 第一点
  5.         this.reason = reason // 第二点
  6.         while (this.rejectCallbacks.length > 0) {  // 第三点
  7.             this.rejectCallbacks.shift().call(undefined) // 第四点
  8.         }
  9.     }
  10. }
复制代码
then方法实现要点


  • 判断then方法的两个参数onRejected和onFulfilled是否为function。
    1.1 onRejected和onFulfilled都是function,继续执行下一步。
    1.2 onRejected不是function,将onRejected赋值为箭头函数,参数为reason执行throw reason
    1.3 onFulfilled不是function,将onFulfilled赋值为箭头函数,参数为value执行return value
  • 当前Promise状态为rejected
    2.1 onRejected方法传入this.reason参数,异步执行。
    2.2 对执行的onRejected方法做容错处理,catch错误作为reject方法参数执行。
  • 当前Promise状态为fulfilled
    3.1 onFulfilled方法传入this.value参数,异步执行。
    3.2 对执行的onFulfilled方法做容错处理,catch错误作为reject方法参数执行。
  • 当前Promise状态为pending
    4.1 收集onFulfilled和onRejected两个回调函数分别push给resolveCallbacks和rejectCallbacks。
    4.2 收集的回调函数同样如上所述,先做异步执行再做容错处理
  • 返回一个 Promise 实例对象。
  1. // 2.2. then 方法
  2. then(onFulfilled, onRejected) {
  3.     onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value // 第一点
  4.     onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason } // 第一点
  5.     const p2 = new myPromise((resolve, reject) => {
  6.         if (this.state === 'rejected') { // 第二点
  7.             queueMicrotask(() => {
  8.                 try {
  9.                     onRejected(this.reason)
  10.                 } catch (e) {
  11.                     reject(e)
  12.                 }
  13.             })
  14.         } else if (this.state === 'fulfilled') { // 第三点
  15.             queueMicrotask(() => {
  16.                 try {
  17.                     onFulfilled(this.value)
  18.                 } catch (e) {
  19.                     reject(e)
  20.                 }
  21.             })
  22.         } else if (this.state === 'pending') { // 第四点
  23.             this.resolveCallbacks.push(() => {
  24.                 queueMicrotask(() => {
  25.                     try {
  26.                         onFulfilled(this.value)
  27.                     } catch (e) {
  28.                         reject(e)
  29.                     }
  30.                 })
  31.             })
  32.             this.rejectCallbacks.push(() => {
  33.                 queueMicrotask(() => {
  34.                     try {
  35.                         onRejected(this.reason)
  36.                     } catch (e) {
  37.                         reject(e)
  38.                     }
  39.                 })
  40.             })
  41.         }
  42.     })
  43.     return p2 // 第五点
  44. }
复制代码
Promise 解决程序(resolvePromise方法)

旁白:其实这个解决程序才是实现核心Promise最难的一部分。因为Promise A+规范对于这部分说的比较绕。
我们直击其实现要点,能跑通所有官方用例就行。如下:

  • 如果x和promise引用同一个对象:
    1.1 调用reject方法,其参数为new TypeError()
  • 如果x是一个promise或x是一个对象或函数:
    2.1 定义一个called变量用于记录then.call参数中两个回调函数的调用情况。
    2.2 定义一个then变量等于x.then
    2.3 then是一个函数。使用call方法绑定x对象,传入解决回调函数拒绝回调函数作为参数。同时利用called变量记录then.call参数中两个回调函数的调用情况。
    2.4 then不是函数。调用resolve方法解决Promise,其参数为x
    2.5 对以上 2.2 检索属性和 2.3 调用方法的操作放在一起做容错处理。catch错误作为reject方法参数执行。同样利用called变量记录then.call参数中两个回调函数的调用情况。
  • 如果x都没有出现以上两种状况:
    调用resolve方法解决Promise,其参数为x
  1. // 2.3 Promise解决程序
  2. function resolvePromise(p2, x, resolve, reject) {
  3.     if (x === p2) {
  4.         // 2.3.1 如果promise和x引用同一个对象
  5.         reject(new TypeError())
  6.     } else if ((x !== null && typeof x === 'object') || typeof x === 'function') {
  7.         // 2.3.2 如果x是一个promise
  8.         // 2.3.3 如果x是一个对象或函数
  9.         let called
  10.         try {
  11.             let then = x.then // 检索x.then属性,做容错处理
  12.             if (typeof then === 'function') {
  13.                 then.call(x, // 使用call绑定会立即执行then方法,做容错处理
  14.                     (y) => { // y也可能是一个Promise,递归调用直到y被resolve或reject
  15.                         if (called) { return }
  16.                         called = true
  17.                         resolvePromise(p2, y, resolve, reject)
  18.                     },
  19.                     (r) => {
  20.                         if (called) { return }
  21.                         called = true
  22.                         reject(r)
  23.                     }
  24.                 )
  25.             } else {
  26.                 resolve(x)
  27.             }
  28.         } catch (e) {
  29.             if (called) { return }
  30.             called = true
  31.             reject(e)
  32.         }
  33.     } else {
  34.         resolve(x)
  35.     }
  36. }
复制代码
called变量的作用:记录then.call传入参数(两个回调函数)的调用情况
根据Promise A+ 2.3.3.3.3规范:两个参数作为函数第一次调用优先,以后的调用都会被忽略。
因此我们在以上两个回调函数中这样处理:

  • 已经调用过一次:此时called已经为true,直接return忽略
  • 首次调用:此时called为undefined,调用后called设为true
注意:2.3 中的catch可能会发生(两个回调函数)已经调用但出现错误的情况,因此同样按上述说明处理。
运行官方测试用例

在完成上面的代码后,我们最终整合如下:
  1. class myPromise {
  2.     constructor(func) {
  3.         this.state = 'pending'
  4.         this.value = undefined
  5.         this.reason = undefined
  6.         this.resolveCallbacks = []
  7.         this.rejectCallbacks = []
  8.         try {
  9.             func(this.resolve, this.reject)
  10.         } catch (e) {
  11.             this.reject(e)
  12.         }
  13.     }
  14.     resolve = (value) => {
  15.         if (this.state === 'pending') {
  16.             this.state = 'fulfilled'
  17.             this.value = value
  18.             while (this.resolveCallbacks.length > 0) {
  19.                 this.resolveCallbacks.shift().call(undefined)
  20.             }
  21.         }
  22.     }
  23.     reject = (reason) => {
  24.         if (this.state === 'pending') {
  25.             this.state = 'rejected'
  26.             this.reason = reason
  27.             while (this.rejectCallbacks.length > 0) {
  28.                 this.rejectCallbacks.shift().call(undefined)
  29.             }
  30.         }
  31.     }
  32.     then(onFulfilled, onRejected) {
  33.         onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
  34.         onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
  35.         const p2 = new myPromise((resolve, reject) => {
  36.             if (this.state === 'rejected') {
  37.                 queueMicrotask(() => {
  38.                     try {
  39.                         const x = onRejected(this.reason)
  40.                         resolvePromise(p2, x, resolve, reject)
  41.                     } catch (e) {
  42.                         reject(e)
  43.                     }
  44.                 })
  45.             } else if (this.state === 'fulfilled') {
  46.                 queueMicrotask(() => {
  47.                     try {
  48.                         const x = onFulfilled(this.value)
  49.                         resolvePromise(p2, x, resolve, reject)
  50.                     } catch (e) {
  51.                         reject(e)
  52.                     }
  53.                 })
  54.             } else if (this.state === 'pending') {
  55.                 this.resolveCallbacks.push(() => {
  56.                     queueMicrotask(() => {
  57.                         try {
  58.                             const x = onFulfilled(this.value)
  59.                             resolvePromise(p2, x, resolve, reject)
  60.                         } catch (e) {
  61.                             reject(e)
  62.                         }
  63.                     })
  64.                 })
  65.                 this.rejectCallbacks.push(() => {
  66.                     queueMicrotask(() => {
  67.                         try {
  68.                             const x = onRejected(this.reason)
  69.                             resolvePromise(p2, x, resolve, reject)
  70.                         } catch (e) {
  71.                             reject(e)
  72.                         }
  73.                     })
  74.                 })
  75.             }
  76.         })
  77.         return p2
  78.     }
  79. }
  80. function resolvePromise(p2, x, resolve, reject) {
  81.     if (x === p2) {
  82.         reject(new TypeError())
  83.     } else if ((x !== null && typeof x === 'object') || typeof x === 'function') {
  84.         let called
  85.         try {
  86.             let then = x.then
  87.             if (typeof then === 'function') {
  88.                 then.call(x,
  89.                     (y) => {
  90.                         if (called) { return }
  91.                         called = true
  92.                         resolvePromise(p2, y, resolve, reject)
  93.                     },
  94.                     (r) => {
  95.                         if (called) { return }
  96.                         called = true
  97.                         reject(r)
  98.                     }
  99.                 )
  100.             } else {
  101.                 resolve(x)
  102.             }
  103.         } catch (e) {
  104.             if (called) { return }
  105.             called = true
  106.             reject(e)
  107.         }
  108.     } else {
  109.         resolve(x)
  110.     }
  111. }
  112. // 新加入部分
  113. myPromise.deferred = function () {
  114.     let result = {};
  115.     result.promise = new myPromise((resolve, reject) => {
  116.         result.resolve = resolve;
  117.         result.reject = reject;
  118.     });
  119.     return result;
  120. }
  121. module.exports = myPromise;
复制代码
新建一个文件夹,放入我们的 myPromise.js 并在终端执行以下命令:
  1. npm init -y
  2. npm install promises-aplus-tests
复制代码
package.json 文件修改如下:
  1. {
  2.   "name": "promise",
  3.   "version": "1.0.0",
  4.   "description": "",
  5.   "main": "myPromise.js",
  6.   "scripts": {
  7.     "test": "promises-aplus-tests myPromise"
  8.   },
  9.   "keywords": [],
  10.   "author": "",
  11.   "license": "ISC",
  12.   "devDependencies": {
  13.     "promises-aplus-tests": "^2.1.2"
  14.   }
  15. }
复制代码
开始测试我们的手写Promise,在终端执行以下命令即可:
  1. npm test
复制代码
Promise 其他方法补充

容错处理方法

Promise.prototype.catch()
  1. catch(onRejected) {
  2.     return this.then(undefined, onRejected)
  3. }
复制代码
Promise.prototype.finally()
  1. finally(callback) {
  2.     return this.then(
  3.         value => {
  4.             return myPromise.resolve(callback()).then(() => value)
  5.         },
  6.         reason => {
  7.             return myPromise.resolve(callback()).then(() => { throw reason })
  8.         }
  9.     )
  10. }
复制代码
静态方法

Promise.resolve()
  1. static resolve(value) {
  2.     if (value instanceof myPromise) {
  3.         return value  // 传入的参数为Promise实例对象,直接返回
  4.     } else {
  5.         return new myPromise((resolve, reject) => {
  6.             resolve(value)
  7.         })
  8.     }
  9. }
复制代码
Promise.reject()
  1. static reject(reason) {
  2.     return new myPromise((resolve, reject) => {
  3.         reject(reason)
  4.     })
  5. }
复制代码
Promise.all()
  1. static all(promises) {
  2.     return new myPromise((resolve, reject) => {
  3.         let countPromise = 0 // 记录传入参数是否为Promise的次数
  4.         let countResolve = 0 // 记录数组中每个Promise被解决次数
  5.         let result = [] // 存储每个Promise的解决或拒绝的值
  6.         if (promises.length === 0) { // 传入的参数是一个空的可迭代对象
  7.             resolve(promises)
  8.         }
  9.         promises.forEach((element, index) => {
  10.             if (element instanceof myPromise === false) { // 传入的参数不包含任何 promise
  11.                 ++countPromise
  12.                 if (countPromise === promises.length) {
  13.                     queueMicrotask(() => {
  14.                         resolve(promises)
  15.                     })
  16.                 }
  17.             } else {
  18.                 element.then(
  19.                     value => {
  20.                         ++countResolve
  21.                         result[index] = value
  22.                         if (countResolve === promises.length) {
  23.                             resolve(result)
  24.                         }
  25.                     },
  26.                     reason => {
  27.                         reject(reason)
  28.                     }
  29.                 )
  30.             }
  31.         })
  32.     })
  33. }
复制代码
Promise.race()
  1. static race(promises) {
  2.     return new myPromise((resolve, reject) => {
  3.         if (promises.length !== 0) {
  4.             promises.forEach(element => {
  5.                 if (element instanceof myPromise === true)
  6.                     element.then(
  7.                         value => {
  8.                             resolve(value)
  9.                         },
  10.                         reason => {
  11.                             reject(reason)
  12.                         }
  13.                     )
  14.             })
  15.         }
  16.     })
  17. }
复制代码
上述所有实现代码已放置我的Github仓库。可自行下载测试,做更多优化。
[ https://github.com/chscript/myPromiseA- ]
参考
MDN-Promise
[译]Promise/A+ 规范

来源:https://www.cnblogs.com/chscript/p/16994964.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具