[Easy] LeetCode JS 30 - 2723. Add Two Promises

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2723. Add Two Promises

Question Prompt

Given two promises promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.

// Example 1
Input:
promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)),
promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))
Output: 7
Explanation: The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem.

// Example 2:
Input:
promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)),
promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30))
Output: -2
Explanation: The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2.

Solutions

To tackle this, we can use Promise.all(). Promise.all() takes an array of promises. It returns a new promise that resolves when all input promises have resolved. The resolved value of the new promise is an array containing the resolved values of the input promises in the same order.

There are two main ways to implement it. First way is using then . By using this way, Promise.all([promise1, promise2]) creates a new promise that waits for both input promises to resolve.

The .then() handler receives an array ([result1, result2]) containing the resolved values. We use destructuring to extract them. We return the sum, result1 + result2.

var addTwoPromises = async function (promise1, promise2) {
  return Promise.all([promise1, promise2]).then(([result1, result2]) => {
    return result1 + result2;
  });
};

The second way is using async/await. An async function always returns a promise. The await keyword inside an async function pauses execution until the awaited promise resolves or rejects.

To do it this way, we need to declare addTwoPromises as an async function. Within the async function, the await Promise.all([promise1, promise2]) ensures both promises resolve before continuing.

After getting result1 and result2, we return the sum.

var addTwoPromises = async function (promise1, promise2) {
  const [result1, result2] = await Promise.all([promise1, promise2]);
  return result1 + result2;
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee