...

/

Handlers Executed as Microtasks

Handlers Executed as Microtasks

Discover how handlers are queued and executed as microtasks.

Assigning handlers to settled promises

A fulfillment, rejection, or settlement handler will still be executed even if it’s added after the promise is already settled. This allows us to add new fulfillment and rejection handlers at any time and guarantee that they’ll be called. For example, we have the following:

import fetch from "node-fetch";
const promise = fetch("https://www.educative.io/udata/1kZPll2Qgkd/book.json");

// original fulfillment handler
promise.then(response => {
    console.log(response.status);

    // now add another
    promise.then(response => {
        console.log(response.statusText);
    });
});
Example of handlers

In this code, the fulfillment handler adds another fulfillment handler to the same promise. The promise is already fulfilled at this point, so the new fulfillment handler is added to the microtask queue and called when ready. Rejection and settlement handlers work the same ...