...

/

Unsettled Promises

Unsettled Promises

Learn how unsettled promises are created and executor errors are caught.

We'll cover the following...

Creating unsettled promises

New promises are created using the Promise constructor. This constructor accepts a single argument: a function called the executor, which contains the code to initialize the promise. The executor is passed two functions, resolve() and reject(), as arguments. When the executor has successfully finished, we call the resolve() function to signal that the promise is resolved, or we call the reject() function to indicate that the operation has failed. Here’s an example using the old XMLHttpRequest browser API:

// Browser example

import XMLHttpRequest from 'xhr2';
function requestURL(url) {
    return new Promise((resolve, reject) => {

        const xhr = new XMLHttpRequest();

        // assign event handlers
        xhr.addEventListener("load", () => {
            resolve({
                status: xhr.status,
                text: xhr.responseText
            });
        });

        xhr.addEventListener("error", error => {
            reject(error);
        });

        // send the request
        xhr.open("get", url);
        xhr.send();
    });
}

const promise = requestURL("https://www.educative.io/udata/1kZPll2Qgkd/book.json");

// listen for both fulfillment and rejection
promise.then(response => {
    // fulfillment
    console.log(response.status);
    console.log(response.text);
}, reason => {
    // rejection
    console.error(reason.message);
});
Example of unsettled promises

In this example, we have the following:

  • Lines 4–25: The
...