Here is a deep dive into all the abilities of promises in ES6+.
A Promise in JavaScript is an object representing the eventual completion (or failure) of an asynchronous operation. It has several built-in functions that allow handling asynchronous tasks efficiently.
Let's dive deep into all the functions of a Promise:
1. Creating a Promise
A Promise is created using the new Promise
constructor:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
}, 2000);
});
The executor function takes two arguments:
resolve(value)
: Marks the Promise as fulfilled and returns a value.reject(error)
: Marks the Promise as rejected with an error.
Here's an example of a promise in action:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // Change this to false to simulate an error
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data.");
}
}, 2000); // Simulate network delay
});
}
fetchData()
.then((result) => {
console.log(result); // "Data fetched successfully!"
})
.catch((error) => {
console.error(error); // "Error fetching data."
});
Methods in promises
- resolve
- reject
- all
- allSettled
- race
- any
Resolve 🚀
Returns a resolved Promise with the given value.
const resolvedPromise = Promise.resolve("Resolved!");
resolvedPromise.then(console.log); // "Resolved!"
Reject 🚀
Returns a rejected Promise with the given error.
const rejectedPromise = Promise.reject("Rejected!");
rejectedPromise.catch(console.error); // "Rejected!"
All 🚀
Waits for all Promises in an array to resolve. If one fails, the entire chain rejects.
const p1 = Promise.resolve(1);
const p2 = new Promise((resolve) => setTimeout(resolve, 1000, 2));
const p3 = Promise.reject("Error!");
Promise.all([p1, p2, p3])
.then(console.log)
.catch(console.error); // "Error!"
allSettled 🚀
Waits for all Promises to settle (resolve or reject), returning an array with results.
Promise.allSettled([p1, p2, p3]).then(console.log);
/*
[
{ status: "fulfilled", value: 1 },
{ status: "fulfilled", value: 2 },
{ status: "rejected", reason: "Error!" }
]
*/
race 🚀
Returns the first Promise that settles (either resolve or reject).
const fast = new Promise((resolve) => setTimeout(resolve, 500, "Fast!"));
const slow = new Promise((resolve) => setTimeout(resolve, 1000, "Slow!"));
Promise.race([fast, slow]).then(console.log); // "Fast!"
any 🚀
Returns the first fulfilled Promise, ignoring rejections. Rejects only if all fail.
const fail1 = Promise.reject("Fail 1");
const fail2 = Promise.reject("Fail 2");
const success = new Promise((resolve) => setTimeout(resolve, 300, "Success!"));
Promise.any([fail1, fail2, success]).then(console.log).catch(console.error); // "Success!"
Top comments (0)