Promise.all()
This approach involves using Promise.all() to wait for both promises to resolve and then perform the addition operation.
Syntax:
Promise.all([promise1, promise2]).then((values) => {
const result = values[0] + values[1];
// Handle the result
}).catch((error) => {
// Handle any errors
});
Example: In this example, adding the results of two promises in JavaScript using the Promise.all() method.
const promise1 = new Promise((resolve) => {
setTimeout(() => {
resolve(5);
}, 1000);
});
const promise2 = new Promise((resolve) => {
setTimeout(() => {
resolve(10);
}, 2000);
});
Promise.all([promise1, promise2]).then((values) => {
const result = values[0] + values[1];
console.log(`The sum of two number is:${result}`);
}).catch((error) => {
console.error(error);
});
Output:
JavaScript Program to Add Two Promises
JavaScript Promises provide a powerful tool for asynchronous programming, allowing developers to work with values that may not be immediately available.
We’ll discuss multiple approaches to solve this problem, examining their syntax and providing examples for each approach.
Table of Content
- Chaining
- Promise.all():
- Async/Await
Contact Us