Problem Description
Given two promises that each resolve with a number, create a function that returns a new promise. This new promise should resolve with the sum of the two numbers produced by the input promises.
Key Insights
- Both promises resolve with a number, so no error handling for non-numeric resolution is needed.
- The simple approach is to use a mechanism to wait for both promises to resolve.
- In JavaScript, Promise.all is ideal for this problem.
- For languages that support asynchronous programming, similar constructs (async/await, futures) can be used.
Space and Time Complexity
Time Complexity: O(1) – The operations are constant time once both promises have resolved. Space Complexity: O(1) – Only a fixed amount of extra space is used.
Solution
We will wait until both promises resolve to get their numeric values. In JavaScript, Promise.all can be used to concurrently wait for both promises. This method collects the resolution values into an array and then sums them. In other languages, similar concurrency constructs are used to wait for asynchronous operations (for example, asyncio.gather in Python, CompletableFuture in Java, or std::future in C++). The key idea is to wait for both asynchronous results and then perform a simple arithmetic addition.