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

Parallel Execution of Promises for Individual Results Retrieval

Number: 2898

Difficulty: Medium

Paid? Yes

Companies: N/A


Problem Description

Given an array of functions where each function returns a promise that can either resolve or reject, we need to execute all the promises in parallel and return a promise that resolves with an array of objects. Each object should indicate whether the corresponding promise was fulfilled or rejected. The final result must preserve the order of the original functions. The challenge is to implement this without using the built-in Promise.allSettled().


Key Insights

  • Execute all promise-returning functions concurrently.
  • Maintain the order of results matching the order of the input functions.
  • Use then and catch to capture both resolved values and rejection reasons.
  • Use a counter to determine when all promises have settled without relying on Promise.allSettled().

Space and Time Complexity

Time Complexity: O(n), where n is the number of functions, as we simply iterate over the array. Space Complexity: O(n) for storing the results in an array.


Solution

The solution uses an array to store the result objects at positions corresponding to the input order. For each function, we immediately invoke it to obtain its promise. We then attach both then and catch handlers to the promise to update the result array with an object that denotes "fulfilled" along with its value, or "rejected" along with its error message if an error occurs. A counter is maintained to check when all promises have either resolved or rejected, at which point the main promise is resolved with the result array. This approach leverages the asynchronous nature of promises while manually tracking their individual resolution statuses.


Code Solutions

import asyncio

async def promise_all_settled(functions):
    results = [None] * len(functions)
    
    async def run(fn, index):
        try:
            value = await fn()
            results[index] = {"status": "fulfilled", "value": value}
        except Exception as e:
            results[index] = {"status": "rejected", "reason": str(e)}
    
    await asyncio.gather(*(run(fn, i) for i, fn in enumerate(functions)))
    return results

# Example usage:
# async def main():
#     async def async_resolve():
#         await asyncio.sleep(0.1)
#         return 15
#
#     functions = [lambda: async_resolve()]
#     result = await promise_all_settled(functions)
#     print(result)
#
# asyncio.run(main())
← Back to All Questions