Promises in JavaScript
Hello! In this guide, we’ll explore how Promises work in JavaScript. Promises are used to handle asynchronous operations and are an essential part of modern JavaScript programming. Let's dive in!
1. What is a Promise?​
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises can be in one of three states:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
2. Creating a Promise​
A Promise is created using the new Promise()
constructor, which takes a function (known as the executor) that contains two callback functions: resolve
and reject
.
Example:​
let promise = new Promise(function (resolve, reject) {
// some async operation
let success = true;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});
In this example, the Promise will call resolve
if the operation succeeds and reject
if it fails.
3. Consuming a Promise​
Once a Promise is created, you can use .then()
, .catch()
, and .finally()
to handle its result.
3.1 .then()
​
The .then()
method is used to handle a fulfilled Promise.
Example:​
promise.then(function (result) {
console.log(result); // "Operation successful!"
});
3.2 .catch()
​
The .catch()
method is used to handle a rejected Promise.
Example:​
promise.catch(function (error) {
console.log(error); // "Operation failed!"
});
3.3 .finally()
​
The .finally()
method is executed once the Promise is settled (either fulfilled or rejected), regardless of the outcome.
Example:​
promise.finally(function () {
console.log("Promise is settled.");
});
4. Chaining Promises​
You can chain multiple .then()
calls together. Each .then()
receives the result of the previous .then()
.
Example:​
let promise = new Promise(function (resolve, reject) {
resolve(10);
});
promise
.then(function (result) {
return result * 2;
})
.then(function (result) {
return result + 5;
})
.then(function (result) {
console.log(result); // 25
});
5. Promise Methods​
JavaScript provides several built-in methods to work with multiple Promises.
5.1 Promise.all()
​
The Promise.all()
method takes an array of Promises and returns a new Promise that resolves when all the input Promises resolve, or rejects if any of the Promises reject.
Example:​
let promise1 = Promise.resolve(5);
let promise2 = Promise.resolve(10);
Promise.all([promise1, promise2]).then(function (results) {
console.log(results); // [5, 10]
});
5.2 Promise.race()
​
The Promise.race()
method returns a Promise that resolves or rejects as soon as one of the input Promises resolves or rejects.
Example:​
let promise1 = new Promise(function (resolve) {
setTimeout(() => resolve("First Promise"), 500);
});
let promise2 = new Promise(function (resolve) {
setTimeout(() => resolve("Second Promise"), 100);
});
Promise.race([promise1, promise2]).then(function (result) {
console.log(result); // "Second Promise"
});
5.3 Promise.allSettled()
​
The Promise.allSettled()
method returns a Promise that resolves when all of the input Promises settle (either fulfilled or rejected).
Example:​
let promise1 = Promise.resolve(10);
let promise2 = Promise.reject("Error");
Promise.allSettled([promise1, promise2]).then(function (results) {
console.log(results);
// [
// {status: "fulfilled", value: 10},
// {status: "rejected", reason: "Error"}
// ]
});
6. Async/Await​
The async
and await
keywords allow you to work with Promises in a more readable way, avoiding the need for chaining .then()
.
Example:​
async function fetchData() {
try {
let result = await promise;
console.log(result); // "Operation successful!"
} catch (error) {
console.log(error); // "Operation failed!"
}
}
fetchData();
Promises are essential in managing asynchronous operations in JavaScript, whether you're handling API calls, timers, or other async tasks. By mastering Promises, you can write cleaner and more efficient asynchronous code. Happy coding!