JavaScript Promises
"I Promise a Result!"
Promises were created to make asynchronous JavaScript easier to write and read.
Promises represents the completion or failure of an asynchronous operation.
A promise can be in one of three states:
| pending | operation started (not finished) |
| rejected | operation failed |
| fulfilled | operation completed |
Why Promises?
Callbacks solve timing problems.
But many callbacks become hard to read and hard to maintain.
Example
step1(function(r1) {
step2(r1, function(r2) {
step3(r2, function(r3) {
console.log(r3);
});
});
});
Note
The style above is often called callback hell.
Promises let you write the same logic in a cleaner way.
Creating a Promise
Syntax
let myPromise = new Promise(function(resolve, reject) {
// Code that may take some time
resolve(value); // when successful
reject(value); // when error
});
The promise constructor takes a function with two parameters.
| Parameter | Description |
|---|---|
| resolve | function to run if finishes successfully |
| reject | function to run if finishes with an error |
Promises How To
Here is how to use a Promise:
Example
myPromise.then(
function(value) { /* code if success */ },
function(value) { /* code if error */ }
);
Note
then() takes two arguments, one callback function for success and another for failure.
Both are optional, so you can add a callback function for success or failure only.
Examples
// Create a Promise Object
let myPromise = new Promise(function(resolve, reject) {
ok = true;
// Code that may take some time
if (ok) {
resolve("OK");
} else {
reject("Error");
}
});
// Using then() to display the result
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
// Create a Promise Object
let myPromise = new Promise(function(resolve, reject) {
ok = false;
// Code that may take some time
if (ok) {
resolve("OK");
} else {
reject("Error");
}
});
// Using then() to display the result
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
Note
A promise represents a value that will be available later.
A promise is a container for a future result.
The result can be a value or an error.
The JavaScript Promise Object
A Promise contains both the producing code and calls to the consuming code:
Promise Syntax
let myPromise = new Promise(function(resolve, reject) {
// "Producing Code" (May take some time)
resolve(value); // when successful
reject(value); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if success */ },
function(value) { /* code if error */ }
);
When the producing code obtains the result, it should call one of the two callbacks:
| When | Call |
|---|---|
| Success | resolve(value) |
| Error | reject(value) |
Note
A promise can resolve or reject only once.
Promise Object Properties
A JavaScript Promise object can be:
- Pending
- Fulfilled
- Rejected
The Promise object supports two properties: state and result.
While a Promise object is "pending" (working), the result is undefined.
When a Promise object is "fulfilled", the result is a value.
When a Promise object is "rejected", the result is an error object.
| myPromise.state | myPromise.result |
|---|---|
| "pending" | undefined |
| "fulfilled" | a result value |
| "rejected" | an error object |
Note
You cannot access the Promise properties state and result.
You must use a Promise method to handle promises.
Using then and catch
You do not read a promise result immediately.
You attach code that runs when the promise finishes.
then() runs when a promise is fulfilled.
catch() runs when a promise is rejected.
Examples
let promise = Promise.resolve("OK");
promise
.then(function(value) {
console.log(value);
})
.catch(function(value) {
myDisplayer(value);
});
let promise = Promise.reject("Error");
promise
.then(function(value) {
console.log(value);
})
.catch(function(value) {
myDisplayer(value);
});
Note
When a promise is fulfilled, the then() function runs.
Returning a Promise
Promises become powerful when you return a promise from then().
This creates a clean chain.
Example
function step1() {
return Promise.resolve("A");
}
function step2(value) {
return Promise.resolve(value + "B");
}
function step3(value) {
return Promise.resolve(value + "C");
}
step1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
return step3(value);
})
.then(function(value) {
myDisplayer(value);
});
Note
The chain runs step by step as each promise finishes.
Where to Put catch
You can handle errors at the end of the chain.
A single catch() can catch errors from any step above.
Example
step1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
return step3(value);
})
.catch(function(error) {
console.log(error);
});
This is one reason promises are easier than many nested callbacks.
Common Beginner Mistakes
Forgetting to return a promise breaks the chain.
Example
step1()
.then(function(value) {
step2(value);
})
.then(function(value) {
console.log(value);
});
The second then() runs too early.
It runs because nothing was returned from the first then().
If you start an async step in then(), return it.
Promises and Real JavaScript
Many web APIs return promises.
fetch() is a common example.
Example
fetch("data.json")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
This is promise-based async programming.
JavaScript Promise Examples
To demonstrate the use of promises, we will use the callback examples from the previous chapter:
- Waiting for a Timeout
- Waiting for a File
Waiting for a Timeout
Example Using Callback
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
Example Using Promise
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Waiting for a file
Example using Callback
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myCallback(req.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.send();
}
getFile(myDisplayer);
Example using Promise
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
JavaScript Promise.allSettled()
The Promise.allSettled() method returns a single Promise from a list of promises.
Example
// Create a Promise
const myPromise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, "King");
});
// Create another Promise
const myPromise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "Queen");
});
// Settle All
Promise.allSettled([myPromise1, myPromise2]).then((results) =>
results.forEach((x) => myDisplay(x.status)),
);
Try it Yourself »
Note
Promise.allSettled() means "Just run all promises. I don't care about the results".
Browser Support
Promise.allSettled() is an ES2020 feature.
ES2020 is fully supported in all modern browsers since September 2020:
| Chrome 85 |
Edge 85 |
Firefox 79 |
Safari 14 |
Opera 71 |
| Aug 2020 | Aug 2020 | Mar 2020 | Sep 2020 | Sep 2020 |
JavaScript Promise.withResolvers()
Promise.withResolvers()
is a static method that simplifies the creation and management of Promises.
Promise.withResolvers() provides a more convenient way to access
the resolve and reject functions associated with a Promise outside of its executor function.
Instead of the traditional new Promise((resolve, reject) => { ... }) constructor pattern,
Promise.withResolvers() returns an object containing:
- promise: The newly created Promise instance
- resolve: A function to fulfill the promise with a value
- reject: A function to reject the promise with a reason (error)
Example
<p id="demo">Waiting...</p>
<script>
const {promise, resolve, reject} = Promise.withResolvers();
// You can now use 'resolve' and 'reject' anywhere
// in your code to control the state of 'promise'.
// Simulate async work
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
}, 1000);
// Update the UI when the promise finishes
promise
.then((message) => {
document.getElementById("demo").innerHTML = message;
})
.catch((error) => {
document.getElementById("demo").innerHTML = error;;
});
</script>
Try it Yourself »
Example Explained
- The <p id="demo"> initially shows "Waiting..."
- After 1 second, the promise resolves or rejects
- The result is written into "demo"
The code to simulate async work can be simplified to:
// Simulate async work
setTimeout(() => {
Math.random() > 0.5
? resolve("Operation successful!")
: reject("Operation failed!");
}, 1000);
The then / catch code can be simplified to:
// Set text in then/catch, update DOM in finally
promise
.then((message) => text = message)
.catch((error) => text = error)
.finally(() => {
document.getElementById("demo").innerHTML = text;
});
Try it Yourself »
Example Explained
- .then() or .catch() set the text variable
- .finally() always runs last, no matter success or failure
- The DOM is updated exactly once, cleanly and reliably
Using async/await is the cleanest:
// Use async/await to handle the promise
(async () => {
try {
text = await promise; // Wait for resolve
} catch (err) {
text = err; // Handle reject
}
// Update the UI after promise finishes
document.getElementById("demo").innerHTML = text;
})();
Try it Yourself »
Example Explained
- async/await makes asynchronous code look synchronous
- The DOM is updated after the promise resolves or rejects
- The UI updates in one place (no duplicated innerHTML calls)
Next Chapter
Promises work well, but chains can still become long.
async and await let you write promise
code like normal code.