Event-driven completion
An event listener must complete an asynchronous operation later.
JavaScript · Function
Promise.withResolvers() returns a new promise together with the resolve and reject functions that control it. This makes it convenient to settle a promise from code outside its constructor executor.
Promise.withResolvers() creates a promise together with the resolve and reject functions associated with it. Because those functions are returned in the same scope as the promise, external code such as an event listener can settle it later.
Promise.withResolvers()A plain object containing promise, resolve, and reject properties.
const { promise, resolve, reject } = Promise.withResolvers();
button.addEventListener("click", () => resolve("clicked"));
promise.then((value) => console.log(value));The promise is controlled by an event listener outside the constructor executor.
An event listener must complete an asynchronous operation later.
External callback code needs to report success or failure through one promise.
A compatible Promise subclass should preserve its own promise type.
It returns a plain object with three properties: promise, resolve, and reject. The promise is new, while the two functions settle that promise.
Follow-up: How does it differ from constructing a promise manually? The functions are exposed in the surrounding scope rather than being captured from inside the executor.
It is useful when an event listener or another external callback must resolve or reject a promise. The callback can retain the returned functions and settle the promise when the event occurs.
Follow-up: What problem does this avoid? It avoids having to place the external event logic inside the Promise constructor's executor.
The method is generic and supports Promise subclasses. Calling it with a compatible subclass produces a promise of that subclass type.
Follow-up: What compatibility requirement applies? The subclass constructor must accept a single executor function that receives resolve and reject callbacks.
Promise() constructorPromise subclassesPromise.resolve()Promise.reject()