How Do I Use JavaScript Promises?
A Javascript Promise is a function that represents the eventual resolution or failure of a task. While we’re waiting for the Promise to complete it has an internal status of pending. The Promise settles with a binary outcome: resolved or rejected.
The Promise function accepts two callbacks as arguments, and upon settling it will run one of them. The first callback is called if the Promise resolves. The second callback is called if the Promise rejects. For this reason, a common way to write a Promise is to name the functions resolve() and reject().
function fetchData(file) {
return new Promise((resolve, reject) => {
...
}
Using JavaScript Promises
Wrapping synchronous code in a Promise does not make it asynchronous, but it may appear to be so. Let’s look at an example:
function countToLargeNumber(largeNumber) {
return new Promise((resolve) => {
let count = 0;
while (count < largeNumber) {
count++; // Counting to a large number
}
resolve("Finished counting to " + largeNumber);
});
}
console.log("Starting count...");
countToLargeNumber(1e9)
.then(result => {
console.log(result);
});
console.log("Logging appears before result but is still delayed.");
The Chrome Console output immediately displays:
Starting count...
... and momentarily you’ll see these appear at the same time:
Logging appears before result but is still delayed.
Finished counting to 1000000000
If you ignore timing, the order of the output gives the illusion that Javascript was counting asynchronously. The log appears before the count is completed. However, the main thread was blocked until counting completed. We had to wait for the count to be completed before the log appeared. Therefore, the Promise wrapper did not make our counting function asynchronous. It changed the order of execution but did not make the script faster.
Typically, developers don’t put synchronous tasks in a Promise. Instead we use Promises to wrap asynchronous code, such as setTimeout() or fetch() methods. Learn more about the various asynchronous methods.
function fetchData(file) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
if (req.status === 200) {
resolve(req.responseText);
} else {
reject(Error('Error code: ' + req.status));
}
req.onerror = function() {
reject(Error('Network failure.'))
}
req.open('GET', file);
req.send();
});
}
A Promise is a function that represents the eventual completion of code. It wraps your code and has a status that is either pending or settled. The settled status is either resolved or rejected.
Typically, developers wrap asynchronous code in a Promise to gain access to .then(), .catch(), and .finally() methods, because they allow us to handle the result after the operation settles. Promises let us handle errors and trigger code at the time of completion of a task. Learn more about these methods.
Related posts:
Helpful references:
Have feedback on this topic?