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

Delay the Resolution of Each Promise

Number: 2909

Difficulty: Medium

Paid? Yes

Companies: N/A


Problem Description

Given an array of functions (each returning a promise) and a delay in milliseconds (ms), return a new array of functions. When invoked, each new function will execute the original promise-returning function and then delay its resolution or rejection by an additional ms milliseconds. For example, if the original function’s promise resolves after 30 ms and ms = 50, the new promise resolves after 80 ms (30 + 50).


Key Insights

  • Each function in the new array wraps the original function, adding an extra delay after its promise settles.
  • The additional delay is applied uniformly whether the promise resolves or rejects.
  • The order of promises is preserved, and there is no dependency between them.
  • A helper delay function (or equivalent) is used to wait for ms milliseconds before forwarding the result or error.

Space and Time Complexity

Time Complexity: O(n) because we process each of the n functions to wrap them. Space Complexity: O(n) for storing the new array of delayed functions.


Solution

The solution involves iterating over the input array and creating a wrapper function for each original function. When the wrapper is called, it:

  1. Executes the original function to get its promise.
  2. Waits for the original promise to settle (either resolve or reject).
  3. Uses an additional delay (via a helper delay function) to postpone the final resolution or rejection by ms milliseconds. The key challenge is to correctly chain the original promise with the delay, handling both success and error cases uniformly.

Code Solutions

Below are implementations in Python, JavaScript, C++, and Java.

import asyncio

def delay(ms):
    # Returns a coroutine that completes after ms milliseconds.
    return asyncio.sleep(ms / 1000)

def delayAll(functions, ms):
    # Returns a new list of functions that delay the resolution or rejection by ms milliseconds.
    def create_delayed_function(func):
        async def delayed():
            try:
                # Await the result from the original function.
                result = await func()
            except Exception as error:
                # Wait additional ms milliseconds, then re-raise the error.
                await delay(ms)
                raise error
            # Wait additional ms milliseconds before returning the result.
            await delay(ms)
            return result
        return delayed

    return [create_delayed_function(func) for func in functions]

# Example usage:
# async def example():
#     functions = [
#         lambda: asyncio.sleep(0.03, result=30)  # Resolves after 30 ms.
#     ]
#     delayed_functions = delayAll(functions, 50)
#     result = await delayed_functions[0]()
#     print(result)  # Expected output: 30 (result arrived after 30+50 ms).
#
# asyncio.run(example())
← Back to All Questions