Problem

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.

Examples

Example 1

1
2
3
4
5
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

1
2
3
4
5
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.

Constraints

  • promise1 and promise2 are promises that resolve with a number

Solution

Method 1 – Promise.all for Parallel Resolution

Intuition

The key idea is to wait for both promises to resolve, then add their results. Promise.all allows us to run both promises in parallel and get their resolved values as an array, which we can sum.

Approach

  1. Use Promise.all to wait for both promise1 and promise2 to resolve.
  2. Once both promises resolve, destructure their results into two variables.
  3. Add the two numbers and resolve the sum.
  4. Return the resulting promise.

Code

1
2
3
4
5
6
7
8
/**
 * @param {Promise<number>} promise1
 * @param {Promise<number>} promise2
 * @return {Promise<number>}
 */
var addTwoPromises = function(promise1, promise2) {
  return Promise.all([promise1, promise2]).then(([a, b]) => a + b);
};
1
2
3
function addTwoPromises(promise1: Promise<number>, promise2: Promise<number>): Promise<number> {
  return Promise.all([promise1, promise2]).then(([a, b]) => a + b);
}

Complexity

  • ⏰ Time complexity: O(1) (ignoring the time taken by the promises to resolve, as they run in parallel)
  • 🧺 Space complexity: O(1)