Progressive interpretation of Promise source code (3)

小讴
中文
Follow front-end small Ou , read more original technical articles

Review: Progressive Interpretation of Promise Source Code (1)
Review: Progressive Interpretation of Promise Source Code (2)

complete code + comments , can be read

Promise.prototype.then-source code

/** Promise原型的then属性,指向函数
 * 参数onFulfilled:onResolved处理程序,在期约兑现时执行的回调
 * 参数onRejected:onRejected处理程序,在期约拒绝时执行的回调
 * 支持无限链式回调,每个then()方法返回新的Promise实例
 */
Promise.prototype.then = function (onFulfilled, onRejected) {
  // console.log(this, 'then') // this指向then()前返回的Promise实例
  // console.log(this.constructor) // constructor指向Promise构造函数
  // console.log(this.constructor === Promise) // true

  /* 创建一个新期约实例(相当于new Promise(noop)),传入空方法noop作为执行器函数
     注意:每次调用.then()都创建新的Promise实例,但调用下一个.then()会将上一个Promise实例的_deferreds数组改变(放入下一个的Handler实例)!
  */
  var prom = new this.constructor(noop) // -> var prom = new Promise(noop) -> var prom = new Promise(()=>{})
  // console.log(prom) // Promise { _state: 0, _handled: false, _value: undefined, _deferreds: [] },新期约
  // console.log(new Promise(noop)) // Promise { _state: 0, _handled: false, _value: undefined, _deferreds: [] },同上

  /**
   * handle()方法
   * 参数this:then()前返回的上一个Promise实例
   * 参数new Handler(onFulfilled, onRejected, prom):创建的Handler实例
   */
  handle(this, new Handler(onFulfilled, onRejected, prom))

  return prom // 返回新创建的期约实例,以便链式调用
}

function noop() {}
  • then pointing function in this , points to the current then before returning Promise instance, so this.constructor point Promise constructor
  • Every time Promise.then is called:

    • Use the empty method noop as the executor function and call new this.constructor() create a new empty Promise instance
    • Will also create a Handler instance of 0616fe19c52360, and then call the handle() method
    • In the end, returns the newly created instance 1616fe19c52390, this is for support infinite chain callback
    • "Calling the next .then() will change the _deferreds Promise instance", which can be studied later

Handler constructor-source code

/** Handler构造函数:打包onFulfilled、onRejected和promise,作为一个整体方便后面调用
 * 参数onFulfilled:resolve回调函数
 * 参数onRejected:reject回调函数
 * 参数promise:新的空promise实例
 */
function Handler(onFulfilled, onRejected, promise) {
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null // 是否有成功回调,若没有则赋为null
  this.onRejected = typeof onRejected === 'function' ? onRejected : null // 是否有失败回调,若没有则赋为null
  this.promise = promise // Handler的promise,指向prom,即在.then()中创建的新Promise实例
  // console.log(this.promise, 'new Handler')
  // console.log(this)
}
  • Receive 3 parameters: success callback, failure callback, new empty promise instance

handle()-test code

  • Simplify based on the source code to facilitate stage testing
/** 测试用的handle()方法
 * 参数self:then()前返回的Promise实例
 * 参数deferred:创建的Handler实例
 */
function handle(self, deferred) {
  // console.log(self)
  // console.log(deferred)

  /* deferred为创建的Handler实例
    Handler {
      onFulfilled: [Function (anonymous)], // onFulfilled处理程序,没有则为null
      onRejected: [Function (anonymous)], // onRejected处理程序,没有则为null
      promise: Promise { // promise属性指向一个新的Promise实例
        _state: 0,
        _handled: false,
        _value: undefined,
        _deferreds: []
      }
    }
  */

  /* 如果返回的期约实例的解决值为promise类型,_state=3 */
  while (self._state === 3) {
    self = self._value // 将解决值赋给返回的期约实例
  }

  /* 如果返回的期约实例是pendding状态,_state=0,即还没有执行resolve()或reject()方法 */
  if (self._state === 0) {
    self._deferreds.push(deferred) // 将Handler实例放入实例的_deferrends数组,然后返回,继续等待
    console.log(self)
    return
  }

  /* 标记当前进行的promise._handled为true */
  self._handled = true
  console.log(self)

  /* 通过事件循环异步来做回调的处理(注意:这里是异步的!) */
  Promise._immediateFn(function () {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected // 获取onFulfilled或onRejected处理程序

    /* 如果有onFulfilled或onRejected回调函数,则执行自己的回调 */
    try {
      /**
       * cb()方法:执行onFulfilled或onRejected处理程序
       * 参数self._value:then()前返回的Promise实例的解决值/拒绝理由
       */
      cb(self._value) // 执行回调
    } catch (e) {
      /* 若抛出错误,则调用reject()方法,参数为创建的Handler实例的promise(新Promise实例)和错误原因 */
      reject(deferred.promise, e)
      return
    }
  })
}
  • then _state be processed differently according to the value of 0616fe19c5257c

    • Return to a non-pending then , and finally execute the processing program in 0616fe19c525b7
    • Back of about pending is not performed then processing program, but will then generated Handler put instances then front Promise example _deferreds array
  • Execution then handler is asynchronous , it will only sync to perform all operations are performed in complete

Promise.prototype.then-stage test

new Promise((resolve, reject) => {}).then(() => {
  console.log(3) // then前是未解决的期约,期约解决前不会执行处理程序
})
/* 执行到handle()时,self._state为0,将Handler实例放入实例的_deferrends数组,不再执行后续操作,self为:
  Promise {
    _state: 0,
    _handled: false,
    _value: undefined,
    _deferreds: [
      Handler { 
        onFulfilled: [Function (anonymous)], 
        onRejected: null, 
        promise: Promise {_state: 0, _handled: false, _value: undefined, _deferreds: []}
      }
    ]
  }
*/

new Promise((resolve, reject) => {
  /* 实际执行首个resolve或reject后,后续的resolve或reject不会再执行,这里仅把测试结果合并 */

  resolve(3) // 打印res为3,解决值为基本类型
  /* self为Promise { _state: 1, _handled: true, _value: 3, _deferreds: [] } */
  resolve({ val: 3 }) // 打印res为{ val: 3 },解决值为普通对象
  /* self为Promise { _state: 1, _handled: true, _value: { val: 3 }, _deferreds: [] } */
  resolve(new Promise(() => {})) // 不打印res,解决值为pending的期约实例
  /* self与new Promise((resolve, reject) => {}).then()基本相同,onFulfilled不再是null*/
  resolve(Promise.resolve(3)) // 打印res为3,解决值为fullfilled的期约实例,将fullfilled的解决值赋给self
  /* self为Promise { _state: 1, _handled: true, _value: 3, _deferreds: [] } */
  resolve({
    // 解决值为thenable对象
    value: 3,
    then: function () {
      console.log(this) // { value: 3, then: [Function: then] }
      console.log(this.value) // 3
    },
  })
  /* self与resolve(new Promise(() => {}))相同 */
}).then((res) => {
  console.log(res) // then()前返回的Promise的解决值
})

new Promise((resolve, reject) => {
  reject(3) // 打印res为3
  /* self为Promise { _state: 2, _handled: true, _value: 3, _deferreds: [] } */
}).then(null, (err) => {
  console.log(err) // then()前返回的Promise的拒绝理由
})
  • There is roughly the prototype of chain callback:

    • According to Promise instance, get its resolution value/rejection reason, and execute the corresponding processing procedure ( onResolve or onReject )
  • pedding of call state about then later, will then generated Handler instance into its _deferreds array

Promise.prototype.catch-source code

/** Promise原型的catch属性,指向函数
 * 参数onRejected:onRejected处理程序,在期约拒绝时执行的回调
 * 支持无限链式回调,每个catch()方法返回新的Promise实例
 */
Promise.prototype['catch'] = function (onRejected) {
  return this.then(null, onRejected)
}
  • Make a layer of encapsulation on Promise.prototype.then onRejected processing program

Promise.prototype.catch-stage test

new Promise((resolve, reject) => {}).catch(() => {
  console.log(3) // catch前是未解决的期约,期约解决前不会执行处理程序(同then)
})

new Promise((resolve, reject) => {
  /* 实际执行首个resolve或reject后,后续的resolve或reject不会再执行,这里仅把测试结果合并 */

  reject(4) // 4,拒绝理由为基本类型
  /* self为Promise { _state: 2, _handled: true, _value: 4, _deferreds: [] } */
  reject({ val: 4 }) // { val: 4 },拒绝理由为普通对象
  /* self为Promise { _state: 2, _handled: true, _value: { val: 4 }, _deferreds: [] } */
  throw Error('error!') // 'Error: error!',抛出错误
  /* self为Promise { _state: 2, _handled: true, _value: Error: error!, _deferreds: [] } */
  reject(new Promise(() => {})) // 'Promise { _state: 0, _handled: false, _value: undefined, _deferreds: [] }',期约本身作为拒绝理由(需与resolve区分)
  /* self为Promise { _state: 2, _handled: true, _value: Promise { _state: 0, _handled: false, _value: undefined, _deferreds: [] }, _deferreds: [] } */
  reject(Promise.resolve(3)) // 'Promise { _state: 1, _handled: false, _value: 3, _deferreds: [] }',同上,期约本身作为拒绝理由,与期约状态无关
  /* self为Promise { _state: 2, _handled: true, _value: Promise { _state: 1, _handled: false, _value: 3, _deferreds: [] }, _deferreds: [] } */
}).catch((err) => {
  console.log(err) // catch()前返回的Promise的拒绝理由
})
  • And Promise.prototype.then result is substantially the same, the need to distinguish catch refusal is about early Promise case of the example

Summary of results achieved

  • Chain callback of a single Promise.prototype.then and Promise.prototype.catch (multiple have not yet been implemented)

code as of this section →

阅读 343
202 声望
14 粉丝
0 条评论
202 声望
14 粉丝
文章目录
宣传栏