Unsettled Promises
Explore how to create unsettled promises using the Promise constructor with an executor function that immediately runs, calling resolve or reject based on asynchronous events. Understand the timing of promise resolution, the role of microtasks, and how errors thrown inside executors trigger rejection handlers, preparing you to write more reliable asynchronous JavaScript code.
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);
});In this example, we have the following:
- Lines 4–25: