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:
- Using
Promise.all
to wait for bothpromise1
andpromise2
to resolve. - Once both promises are resolved, we will add their resolved values together.
- The final result will be returned as a new promise that resolves with the sum.