Creating promises in Javascript - Performance & Efficiency
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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop creatingnpromises. - How many times: Exactly
ntimes, once per promise.
Each promise is created one after another, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 promise creations |
| 100 | 100 promise creations |
| 1000 | 1000 promise creations |
Pattern observation: The work increases evenly as we add more promises.
Time Complexity: O(n)
This means the time to create all promises grows in a straight line with the number of promises.
[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.
Understanding how promise creation scales helps you write efficient asynchronous code and explain your reasoning clearly in interviews.
"What if we created promises inside a nested loop? How would the time complexity change?"
Practice
resolve function do inside a JavaScript Promise?Solution
Step 1: Understand the role of
Theresolvein promisesresolvefunction is called when the asynchronous task finishes successfully.Step 2: Differentiate from
rejectrejectis used for failure, soresolvemust mean success.Final Answer:
It marks the promise as successfully completed. -> Option CQuick Check:
resolve = success [OK]
- Confusing resolve with reject
- Thinking resolve cancels the promise
- Believing resolve pauses execution
Solution
Step 1: Recall the Promise constructor syntax
The Promise constructor takes a single function with two parameters: resolve and reject, wrapped in parentheses.Step 2: Check each option for correct syntax
new Promise((resolve, reject) => { }) correctly usesnew Promise((resolve, reject) => { }). Others have syntax errors.Final Answer:
new Promise((resolve, reject) => { }) -> Option DQuick Check:
Promise syntax = new Promise((resolve, reject) => { }) [OK]
- Missing parentheses around parameters
- Using wrong keyword order
- Incorrect arrow function syntax
const p = new Promise((resolve, reject) => {
resolve('Done');
});
p.then(result => console.log(result));Solution
Step 1: Understand promise resolution
The promise callsresolve('Done'), so it completes successfully with value 'Done'.Step 2: Check what
thendoesthenreceives the resolved value and logs it, so 'Done' is printed.Final Answer:
Done -> Option AQuick Check:
Resolved value logged = Done [OK]
- Expecting undefined instead of resolved value
- Confusing promise object with resolved output
- Thinking promise logs automatically
const p = new Promise(resolve, reject) => {
resolve('Success');
};Solution
Step 1: Check Promise constructor usage
The Promise constructor requires a single function argument wrapped in parentheses.Step 2: Identify arrow function syntax error
The code usesnew Promise(resolve, reject) => { }which is invalid syntax. It should benew Promise((resolve, reject) => { }).Final Answer:
Arrow function syntax is incorrect for Promise constructor. -> Option BQuick Check:
Arrow function must be inside parentheses [OK]
- Not wrapping parameters in parentheses
- Omitting new keyword (not in this case)
- Using wrong arrow function syntax
Solution
Step 1: Understand how to delay resolution
UsesetTimeoutto delay callingresolveby 1000 ms (1 second).Step 2: Check each option for correct usage
new Promise((resolve) => { setTimeout(() => resolve('Done'), 1000); }) correctly passes a function to Promise and callsresolve('Done')insidesetTimeout. new Promise(resolve => setTimeout(resolve('Done'), 1000)) calls resolve immediately. new Promise((resolve, reject) => { resolve('Done'); setTimeout(() => {}, 1000); }) resolves immediately and delays nothing. new Promise(() => { setTimeout(() => resolve('Done'), 1000); }) does not receive resolve parameter.Final Answer:
new Promise((resolve) => { setTimeout(() => resolve('Done'), 1000); }) -> Option AQuick Check:
Delay resolve with setTimeout inside Promise [OK]
- Calling resolve immediately instead of inside setTimeout
- Not passing resolve parameter
- Placing setTimeout outside Promise
Ready to prove it?
Pass the test and this pattern moves unknown
