Promise.withResolvers()
The Promise.withResolvers()
method is a powerful addition to JavaScript’s Promise API. Let’s explore what it does and how you can use it:
What Is
Promise.withResolvers()
?- The
Promise.withResolvers()
static method returns an object containing:- A new Promise object.
- Two functions:
resolve
andreject
.
- These functions correspond to the two parameters passed to the executor of the
Promise()
constructor.
- The
Syntax:
JavaScriptconst { promise, resolve, reject } = Promise.withResolvers();
- The
promise
is the newly created Promise. - The
resolve
function resolves the promise (similar to theresolve
function in the Promise constructor). - The
reject
function rejects the promise (similar to thereject
function in the Promise constructor).
- The
Example: Transforming a Stream to an Async Iterable
- Imagine you have a Node.js readable stream that you want to convert into an async iterable.
- Each promise represents a single batch of data available from the stream.
- Event listeners are attached once, but they call different versions of
resolve
andreject
each time:JavaScriptasync function* readableToAsyncIterable(stream) { let { promise, resolve, reject } = Promise.withResolvers(); stream.on("error", (error) => reject(error)); stream.on("end", () => resolve()); stream.on("readable", () => resolve()); while (stream.readable) { await promise; let chunk; while ((chunk = stream.read())) { yield chunk; } ({ promise, resolve, reject } = Promise.withResolvers()); } }
Calling
withResolvers()
on a Non-Promise ConstructorPromise.withResolvers()
is generic and can be called on any constructor that implements the same signature as thePromise()
constructor.- For example, you can call it on a custom constructor that passes
console.log
as the resolve and reject functions to the executor.
Benefits and Use Cases:
- Conciseness: It’s more concise than manually creating a Promise with
resolve
andreject
. - Advanced Scenarios: The resolution and rejection functions live in the same scope as the promise, enabling advanced use cases (e.g., recurring events, streams, and queues).
- Conciseness: It’s more concise than manually creating a Promise with
Remember, Promise.withResolvers()
simplifies promise creation and opens up possibilities for more elegant and efficient code! 🚀🌟 1: MDN Web Docs - Promise.withResolvers()
Comments
Post a Comment