#2721

Execute Asynchronous Functions in Parallel

Medium
Promise HandlingAsynchronous Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the ability to execute all promises in parallel and uses a single promise to track their completion. This is efficient and ensures we handle both resolution and rejection correctly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create an array to hold the results and a counter for completed promises.
  2. 2Step 2: Return a new promise that will resolve or reject based on the results of the async functions.
  3. 3Step 3: Loop through each function, call it, and attach .then() and .catch() to handle results.
  4. 4Step 4: On resolution, store the result and check if all promises are resolved. If so, resolve the main promise with the results array.
  5. 5Step 5: On rejection, immediately reject the main promise with the error.
solution.py19 lines
1def promiseAll(functions):
2    results = []
3    completed = 0
4    def resolver(index):
5        nonlocal completed
6        def inner(promise):
7            try:
8                result = promise()
9                results[index] = result
10                completed += 1
11                if completed == len(functions):
12                    return Promise.resolve(results)
13            except Exception as e:
14                return Promise.reject(e)
15        return inner
16    for i, func in enumerate(functions):
17        results.append(None)
18        resolver(i)(func)
19    return Promise.reject('Error')

Complexity note: The time complexity is O(n) because we are handling each promise independently in parallel. The space complexity is O(n) due to the results array that stores the resolved values.

  • 1Understanding how promises work in parallel is crucial for efficient asynchronous programming.
  • 2Handling both resolution and rejection properly is key to building robust asynchronous functions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.