0
0
Javascriptprogramming~5 mins

Creating promises in Javascript - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: Creating promises
O(n)
Understanding Time Complexity

When we create promises in JavaScript, we want to know how the time to create and run them changes as we add more promises.

We ask: How does the work grow when we make many promises?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const createPromises = (n) => {
  const promises = [];
  for (let i = 0; i < n; i++) {
    promises.push(new Promise((resolve) => {
      setTimeout(() => resolve(i), 100);
    }));
  }
  return Promise.all(promises);
};
    

This code creates an array of n promises that each resolve after a short delay, then waits for all to finish.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop creating n promises.
  • How many times: Exactly n times, once per promise.
How Execution Grows With Input

Each promise is created one after another, so the work grows directly with n.

Input Size (n)Approx. Operations
1010 promise creations
100100 promise creations
10001000 promise creations

Pattern observation: The work increases evenly as we add more promises.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all promises grows in a straight line with the number of promises.

Common Mistake

[X] Wrong: "Creating many promises runs instantly and does not depend on how many there are."

[OK] Correct: Even though promises run asynchronously, creating each one takes time, so more promises mean more work upfront.

Interview Connect

Understanding how promise creation scales helps you write efficient asynchronous code and explain your reasoning clearly in interviews.

Self-Check

"What if we created promises inside a nested loop? How would the time complexity change?"