跪拜 Guibai
← All articles
Frontend

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

By excel ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Anyone extending Promise with custom behavior needs to know that the parent constructor executes the wrapped executor synchronously, before the subclass finishes assigning its own state. A progress callback that fires too early gets dropped without an error, so the subclass can look correct while losing notifications.

Summary

Subclassing Promise in JavaScript works by handing the parent constructor a wrapper function. In a `NotifiablePromise` subclass, that wrapper is passed to `super()` as the executor; the `Promise` constructor creates `resolve` and `reject`, then synchronously calls the wrapper with both. The wrapper forwards them into the original executor and adds a third `notify` argument for progress reporting.

Because `Promise` invokes its executor synchronously, any `notify()` call made during the initial execution of the original executor runs before `notifyFn` has been assigned. The notification is silently ignored. Calling `notify` inside a timer, network callback, or other asynchronous task keeps the assignment in place and avoids the dropped callback.

Takeaways
— `super()` in a Promise subclass invokes the parent `Promise` constructor with the wrapped executor.
— The `Promise` constructor creates `resolve` and `reject`, then immediately calls the executor with both functions.
— The wrapper receives `resolve` and `reject` from `super()` and forwards them to the original executor, adding a third `notify` argument.
— The subclass assigns `notifyFn` only after `super()` returns; the original executor runs before that assignment.
— A synchronous `notify()` call in the original executor is ignored because `notifyFn` is not assigned yet.
— Calling `notify` inside timers, network requests, or other async tasks avoids the dropped-notification problem.
Conclusions

Promise subclassing splits initialization across the parent's synchronous executor and the subclass's post-`super` code, which makes ordering bugs easy to introduce.

Losing an early notification silently rather than throwing makes this failure mode hard to detect outside a test that exercises a synchronous `notify` call.

Concepts & terms
executor
The function passed to a Promise constructor. The Promise implementation creates `resolve` and `reject`, then synchronously calls the executor with both functions so the promise can be settled later.
super() in a subclass constructor
In a class extending Promise, `super(...)` invokes the parent Promise constructor with the executor argument, allowing the parent to create the promise, call the executor, and return a thenable object before the subclass finishes its own initialization.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗