Advanced Promise Methods
Promise.allSettled() Method
Waits for all promises to settle (fulfilled or rejected) and returns results.
Promise.allSettled([
Promise.resolve("Task 1 completed"),
Promise.reject("Task 2 failed"),
Promise.resolve("Task 3 completed")
])
.then((results) => console.log(results));
//[{"status":"fulfilled","value":"Task 1 completed"},{"status":"rejected","reason":"Task 2 failed"},{"status":"fulfilled","value":"Task 3 completed"}]
Promise.race() Method
Promise.race() Method resolves or rejects as soon as the first promise settles.
Promise.race([
new Promise((resolve) =>
setTimeout(() =>
resolve("Task 1 finished"), 1000)),
new Promise((resolve) =>
setTimeout(() =>
resolve("Task 2 finished"), 500)),
]).then((result) =>
console.log(result))
.catch(err => console.error(err));
//Task 2 finished
Async and Await in JavaScript
Async/Await in JavaScript allows you to write asynchronous code in a clean, synchronous-like manner, making it easier to read, understand, and maintain while working with promises.
- async functions always return a Promise.
- await pauses execution until the Promise is resolved or rejected.
- Improves readability compared to .then() and .catch() chaining.
- Makes error handling simpler using try...catch.
- Ideal for managing complex asynchronous flows in a structured way. Syntax:
async function functionName() {
try {
const result = await someAsyncFunction();
console.log(result);
} catch (error) {
console.error("Error:", error.message);
}
}
Await Keyword
The await keyword pauses the execution of an async function until a Promise is resolved or rejected. It can only be used inside an async function, making asynchronous code easier to read and manage.
- Used to wait for a Promise to settle.
- Can only be used inside async functions.
- Prevents callback and .then() chaining.
- Makes asynchronous code cleaner and more readable.
- Supports error handling with try...catch.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data Loaded");
}, 2000);
});
}
async function displayData() {
const result = await fetchData();
console.log(result);
}
displayData();
//Data Loaded
Explanation
fetchData() returns a Promise.await fetchData() waits until the Promise resolves.Once resolved, the value is stored in result.The remaining code executes.
Use try...catch with async/await.
function divide(a, b) {
return new Promise((resolve, reject) => {
if (b === 0) {
reject("Cannot divide by zero");
} else {
resolve(a / b);
}
});
}
async function calculate() {
try {
const result = await divide(10, 2);
console.log(result);
} catch (error) {
console.log(error);
}
}
calculate();
//5
Should we always use resolve() first?
No. There is no rule that resolve() must come first. We call either resolve() or reject() based on the condition. If the operation succeeds, we use resolve(). If it fails, we use reject(). Only one of them can be called for a Promise.
References
https://www.geeksforgeeks.org/javascript/javascript-promise/
https://www.geeksforgeeks.org/javascript/async-await-function-in-javascript/
Top comments (0)