跪拜 Guibai
← Back to the summary

Why `super()` Can Receive `resolve` and `reject` in a Promise Subclass

Why can resolve and reject be received in super?

In this code:

class NotifiablePromise extends Promise {
  constructor(executor) {
    let notifyFn;

    super((resolve, reject) => {
      executor(resolve, reject, (progress) => {
        if (notifyFn) notifyFn(progress);
      });
    });

    this._listeners = [];
    notifyFn = (progress) => {
      this._listeners.forEach(fn => fn(progress));
    };
  }
}

Because NotifiablePromise inherits from Promise, super(...) in the constructor means calling the parent class Promise constructor.

The value passed to super is a function:

(resolve, reject) => {
  // ...
}

That function is the executor passed to Promise. The Promise constructor creates two functions, resolve and reject, and immediately calls the executor:

executor(resolve, reject);

Therefore, the resolve and reject here are parameters supplied by the Promise constructor. The subclass receives them through the wrapper function and then passes them to the original executor passed in when creating NotifiablePromise:

executor(resolve, reject, notify);

The execution flow can be simplified as:

super(wrapper)
  ↓
Promise constructor calls wrapper(resolve, reject)
  ↓
wrapper forwards resolve and reject to the original executor

For example:

const promise = new NotifiablePromise((resolve, reject, notify) => {
  setTimeout(() => {
    notify(50);
    resolve("完成");
  }, 1000);
});

Here, the resolve and reject in the original executor are the functions created by the parent Promise and passed down; notify is the third parameter added by the subclass, used to send progress notifications.

Note that Promise synchronously calls the executor passed to it. Therefore, if the original executor calls notify during synchronous execution, notifyFn may not have been assigned yet, and the notification will be ignored. Calling notify inside asynchronous tasks such as timers or network requests avoids this problem.

In summary: super calls the parent class Promise constructor; the Promise constructor then passes resolve and reject to the executor it receives.