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

Number: 2859

Difficulty: Easy

Paid? No

Companies: Google


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.


Code Solutions

import asyncio

# Define an asynchronous function to add two "promises"
async def add_two_promises(promise1, promise2):
    # Wait concurrently for both asynchronous operations to complete
    result1, result2 = await asyncio.gather(promise1, promise2)
    # Return the sum of the resolved numbers
    return result1 + result2

# Example usage
async def main():
    # Simulate each promise with asyncio.sleep and then return a value
    async def promise1():
        await asyncio.sleep(0.02)  # simulate delay (20ms)
        return 2

    async def promise2():
        await asyncio.sleep(0.06)  # simulate delay (60ms)
        return 5

    # Get the sum of two "promises"
    result = await add_two_promises(promise1(), promise2())
    print(result)  # Expected output: 7

# Running the example
if __name__ == "__main__":
    asyncio.run(main())
← Back to All Questions