Promises
A Promise in JavaScript is conceptually identical to a promise made in real life: it is a commitment that something will happen in the future.
A Promise has two potential outcomes:
- It is fulfilled (resolved): The operation succeeded.
- It is rejected: The operation failed.
While we wait for the Promise to reach one of these two states, our main code continues executing. Promises are the modern standard for writing asynchronous code in JavaScript.
Creating a Promise
You create a Promise using the new Promise() constructor, which accepts a callback function containing two built-in arguments: resolve and reject.
const myPromise = new Promise((resolve, reject) => {
// Simulate an async task taking 1 second
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("The operation succeeded!");
} else {
reject("The operation failed!");
}
}, 1000);
});
Working with Promises
Once you have a Promise object, how do you actually receive its data when it finishes?
You chain the .then() and .catch() methods onto the Promise object.
.then()executes if the promise callsresolve()..catch()executes if the promise callsreject().
myPromise
.then((message) => {
// Runs if successful
console.log(`Success: ${message}`);
})
.catch((errorMessage) => {
// Runs if it fails
console.log(`Error: ${errorMessage}`);
});