How to understand the safeThen function in Promise source code?

Source code see here

Promise.prototype.then = function(onFulfilled, onRejected) {
  if (this.constructor !== Promise) {
    return safeThen(this, onFulfilled, onRejected);
  }
  var res = new Promise(noop);
  handle(this, new Handler(onFulfilled, onRejected, res));
  return res;
};

function safeThen(self, onFulfilled, onRejected) {
  return new self.constructor(function (resolve, reject) {
    // 
    var res = new Promise(noop);
    res.then(resolve, reject);
    handle(self, new Handler(onFulfilled, onRejected, res));
  });
}
Mar.06,2021

I haven't done much research. This should be a Promise implementation of some polyfill, isn't it? The Promise of V8 should be written by cpp.

this code seems to be designed to make some subclasses that inherit from Promise work properly.


it's best to attach the source of this code, because Promise has a lot of implementations, so it's hard to see what the author thinks.

there is another way to find the submission record for this line and see what the author thinks when he writes it.


like

const getVal = new P(resolve => resolve('todo'));
getVal.then.bind(window).then((val) => { console.log(val) });

// bindthensafeThen
Menu