We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Add Two Promises

Difficulty: Easy


Problem Description

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.


Key Insights

  • Both input promises resolve with numerical values.
  • The output promise should resolve after both input promises have resolved.
  • The order in which the promises resolve does not affect the final result.

Space and Time Complexity

Time Complexity: O(1) - The operations performed are constant time. Space Complexity: O(1) - Only a fixed amount of space is used for handling the input promises and the result.


Solution

To solve the problem, we will use the Promise.all method which takes an array of promises and returns a new promise that resolves when all of the input promises have resolved. We will then sum the resolved values of the two promises. The approach involves:

  1. Using Promise.all to wait for both promise1 and promise2 to resolve.
  2. Once both promises are resolved, we will add their resolved values together.
  3. The final result will be returned as a new promise that resolves with the sum.

Code Solutions

function addTwoPromises(promise1, promise2) {
    return Promise.all([promise1, promise2]) // Wait for both promises to resolve
        .then(values => values[0] + values[1]); // Sum the resolved values
}
← Back to All Questions