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.