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:

  1. What Is Promise.withResolvers()?

    • The Promise.withResolvers() static method returns an object containing:
      • A new Promise object.
      • Two functions: resolve and reject.
    • These functions correspond to the two parameters passed to the executor of the Promise() constructor.
  2. Syntax:

    JavaScript
    const { promise, resolve, reject } = Promise.withResolvers();
    
    • The promise is the newly created Promise.
    • The resolve function resolves the promise (similar to the resolve function in the Promise constructor).
    • The reject function rejects the promise (similar to the reject function in the Promise constructor).
  3. 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 and reject each time:
      JavaScript
      async 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());
        }
      }
      
  4. Calling withResolvers() on a Non-Promise Constructor

    • Promise.withResolvers() is generic and can be called on any constructor that implements the same signature as the Promise() constructor.
    • For example, you can call it on a custom constructor that passes console.log as the resolve and reject functions to the executor.
  5. Benefits and Use Cases:

    • Conciseness: It’s more concise than manually creating a Promise with resolve and reject.
    • 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).

Remember, Promise.withResolvers() simplifies promise creation and opens up possibilities for more elegant and efficient code! 🚀🌟 1MDN Web Docs - Promise.withResolvers()

Comments

Popular posts from this blog

New Tech Bloggie

FinTech App

JavaScript - Object.groupBy()