Execute Asynchronous Functions in Parallel - Problem

Imagine you're a concert conductor who needs to coordinate multiple musicians to play their parts simultaneously. In the programming world, you're tasked with executing multiple asynchronous functions in parallel and collecting their results.

Given an array of asynchronous functions, you need to create a new promise that:

  • โœ… Resolves when all functions complete successfully, returning an array of results in the same order as the input functions
  • โŒ Rejects immediately when any function fails, with the reason from the first rejection

๐Ÿšซ Challenge: You cannot use the built-in Promise.all() function - you must implement this functionality from scratch!

Example: If you have functions that resolve to ["hello", "world", "!"], your promise should resolve to ["hello", "world", "!"] in exactly that order, even if the functions complete in a different sequence.

Input & Output

example_1.js โ€” Basic Success Case
$ Input: functions = [() => Promise.resolve(1), () => Promise.resolve(2), () => Promise.resolve(3)]
โ€บ Output: [1, 2, 3]
๐Ÿ’ก Note: All three functions resolve successfully. The promise resolves with an array containing all results in the original order, even though the functions might complete at different times.
example_2.js โ€” Different Timing
$ Input: functions = [() => delayResolve('fast', 50), () => delayResolve('slow', 200), () => delayResolve('medium', 100)]
โ€บ Output: ['fast', 'slow', 'medium']
๐Ÿ’ก Note: Even though 'fast' completes first (50ms), 'medium' second (100ms), and 'slow' last (200ms), the results maintain the original array order. Total execution time is 200ms (not 350ms) due to parallel execution.
example_3.js โ€” Early Rejection
$ Input: functions = [() => delayResolve('success', 100), () => delayReject('error', 50), () => delayResolve('never seen', 200)]
โ€บ Output: Promise rejects with 'error'
๐Ÿ’ก Note: The second function rejects after 50ms. The entire promise immediately rejects with this error, even though the first function would have succeeded and the third function is still running.

Visualization

Tap to expand
Promise.all Implementation - Orchestra Conductor Analogy๐ŸŽผConductor(Promise Controller)๐ŸŽบFunction 1100ms๐ŸŽทFunction 250ms๐ŸฅFunction 3200msState Tracking DashboardResults: [null, null, null] โ†’ ["trumpet", null, null] โ†’ ["trumpet", "sax", null] โ†’ ["trumpet", "sax", "drums"]Completed Count: 0 โ†’ 1 โ†’ 2 โ†’ 3โœ“ All started simultaneously | โœ“ Order preserved | โœ“ Parallel executionTotal Time: 200ms (max of all) instead of 350ms (sum)
Understanding the Visualization
1
Conductor Raises Baton
Initialize state: results array, completion counter, rejection flag
2
All Musicians Start Playing
Execute all async functions simultaneously - true parallelism
3
Track Each Performance
As each function completes, store result at correct index and increment counter
4
Handle Mistakes Immediately
If any function fails, immediately stop and report the error
5
Complete Performance
When all succeed, return ordered results array
Key Takeaway
๐ŸŽฏ Key Insight: Start all promises simultaneously, track completion with a counter, maintain order with indexed storage, and fail fast on first rejection - this achieves optimal O(max(Tโ‚,Tโ‚‚,...,Tโ‚™)) time complexity instead of O(Tโ‚+Tโ‚‚+...+Tโ‚™).

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(max(Tโ‚, Tโ‚‚, ..., Tโ‚™))

Total time is only as long as the slowest promise since they run in parallel

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Need to store results array and track state for n promises

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค functions.length โ‰ค 103
  • Each function returns a Promise
  • Functions accept no arguments
  • Cannot use built-in Promise.all()
  • Must maintain original order in results
  • Must reject immediately on first failure
Asked in
Meta 45 Google 38 Amazon 35 Microsoft 28 Netflix 22
42.4K Views
Very High Frequency
~25 min Avg. Time
1.8K 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