Problem Description
Given an array of asynchronous functions (each taking no arguments and returning a promise), execute all these functions concurrently. Return a new promise that resolves with an array of resolved values (in the same order as the original functions) if all asynchronous functions resolve successfully, or rejects immediately with the reason of the first rejection if any promise fails.
Key Insights
- The problem requires parallel execution of multiple asynchronous functions.
- The solution mimics the behavior of Promise.all without using the built-in function.
- Create a container (e.g., an array) to hold the results at respective indices.
- Keep track of how many promises have successfully resolved.
- If any promise rejects, immediately reject the final promise with the encountered error.
Space and Time Complexity
Time Complexity: O(n) where n is the number of asynchronous functions (each function is launched concurrently). Space Complexity: O(n) for storing the resolved values as well as auxiliary variables.
Solution
We initiate execution for all asynchronous functions concurrently. For each function:
- Call it immediately to begin execution.
- For a successful resolution, store its result in a results container at the same index as its corresponding function.
- Increase a counter for resolved promises, and once the counter equals the number of functions, resolve the final promise with the results.
- If any promise rejects, immediately reject the final promise with that rejection reason. In this solution, synchronization is handled manually (using counters or atomic variables) without relying on built-in helper methods equivalent to Promise.all.