Execute Asynchronous Functions in Parallel - Problem

Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel.

promise resolves:

When all the promises returned from functions were resolved successfully in parallel. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise should resolve when all the asynchronous functions in the array have completed execution in parallel.

promise rejects:

When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection.

Please solve it without using the built-in Promise.all function.

Input & Output

Example 1 — Basic Parallel Execution
$ Input: functions = [() => new Promise(res => setTimeout(() => res(5), 200))]
Output: [5]
💡 Note: Single promise resolves to 5 after 200ms. The returned promise resolves with [5].
Example 2 — Multiple Promises
$ Input: functions = [() => Promise.resolve(1), () => Promise.resolve(2), () => Promise.resolve(3)]
Output: [1,2,3]
💡 Note: Three promises that resolve immediately to 1, 2, and 3. Results maintain original order.
Example 3 — Promise Rejection
$ Input: functions = [() => Promise.resolve(1), () => Promise.reject('Error'), () => Promise.resolve(3)]
Output: Promise rejects with 'Error'
💡 Note: Second promise rejects, causing the entire result promise to reject with 'Error'.

Constraints

  • functions is a valid array
  • 0 ≤ functions.length ≤ 10
  • functions[i] returns a Promise

Visualization

Tap to expand
Execute Asynchronous Functions in ParallelFunction 1Function 2Function 3ParallelExecutionWait for AllCompleteAll promises execute simultaneouslyResults: [val1, val2, val3]
Understanding the Visualization
1
Input
Array of async functions that return promises
2
Execute
Start all promises simultaneously
3
Collect
Gather results in original order when all complete
Key Takeaway
🎯 Key Insight: Execute all promises immediately but coordinate their completion using manual tracking
Asked in
Meta 25 Google 20 Amazon 18 Microsoft 15
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen