Why promises are used in Javascript - Performance Analysis
We want to understand how using promises affects the time it takes for JavaScript code to run.
Specifically, we ask: How does the program's work grow when promises handle tasks?
Analyze the time complexity of the following code snippet.
function fetchData(urls) {
return Promise.all(urls.map(url => fetch(url)));
}
fetchData(['url1', 'url2', 'url3']).then(results => {
console.log(results);
});
This code fetches data from multiple URLs at the same time using promises.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each URL to start a fetch request.
- How many times: Once for each URL in the input array.
Each URL causes one fetch operation to start, so the total work grows with the number of URLs.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 fetch calls started |
| 100 | 100 fetch calls started |
| 1000 | 1000 fetch calls started |
Pattern observation: The number of operations grows directly with the number of URLs.
Time Complexity: O(n)
This means the time to start all fetches grows linearly with the number of URLs.
[X] Wrong: "Promises make the code run instantly, so time does not grow with input size."
[OK] Correct: Promises start tasks asynchronously but each task still takes time, so more tasks mean more total work.
Understanding how promises affect time helps you explain asynchronous code performance clearly and confidently.
"What if we changed Promise.all to run fetches one after another instead of all at once? How would the time complexity change?"
Practice
Promise helps with:Solution
Step 1: Understand what promises do
Promises allow JavaScript to handle tasks like loading data without freezing the program.Step 2: Identify the correct purpose
Promises help manage asynchronous tasks so the program keeps running smoothly.Final Answer:
Handling tasks that take time without stopping the program -> Option DQuick Check:
Promises = handle async tasks without blocking [OK]
- Thinking promises slow down the program
- Confusing promises with data storage
- Believing promises remove the need for functions
Solution
Step 1: Recall correct Promise syntax
Promises are created withnew Promiseand a function withresolveandrejectparameters.Step 2: Check each option
Only let p = new Promise((resolve, reject) => { /* code */ }); uses the correct syntax withnew Promiseand arrow function.Final Answer:
let p = new Promise((resolve, reject) => { /* code */ }); -> Option AQuick Check:
Correct Promise syntax = new Promise(...) [OK]
- Using lowercase 'promise' instead of 'Promise'
- Trying to call Promise.create which doesn't exist
- Missing parentheses or arrow function syntax
const p = new Promise((resolve) => {
setTimeout(() => resolve('Done'), 100);
});
p.then(result => console.log(result));
console.log('Start');Solution
Step 1: Understand asynchronous behavior
ThesetTimeoutdelays theresolvecall by 100ms, soconsole.log('Start')runs first.Step 2: Trace the output order
First, 'Start' prints immediately, then after 100ms, 'Done' prints from the promise.Final Answer:
Start
Done -> Option AQuick Check:
Async delay means 'Start' before 'Done' [OK]
- Assuming promise resolves immediately
- Thinking 'Done' prints before 'Start'
- Ignoring asynchronous nature of setTimeout
const p = new Promise((resolve, reject) => {
resolve('Success');
reject('Error');
});
p.then(result => console.log(result))
.catch(error => console.log(error));Solution
Step 1: Understand promise state changes
Once a promise is resolved or rejected, its state is final and cannot change.Step 2: Analyze the code flow
The promise callsresolve('Success')first, so the laterreject('Error')is ignored.Final Answer:
Calling reject after resolve has no effect -> Option BQuick Check:
Promise settles once; later calls ignored [OK]
- Thinking reject overrides resolve if called later
- Believing then and catch can't be chained
- Confusing semicolon placement with logic errors
Solution
Step 1: Understand promise chaining for dependent tasks
When one task depends on another, use.then()to wait for the first before starting the second.Step 2: Identify correct chaining
Call fetchUser(), then inside its .then(), call fetchPosts() and return that promise correctly callsfetchUser(), then in its.then(), callsfetchPosts()and returns its promise to chain properly.Final Answer:
Call fetchUser(), then inside its .then(), call fetchPosts() and return that promise -> Option CQuick Check:
Promise chaining = dependent tasks in sequence [OK]
- Running dependent tasks in parallel without waiting
- Using setTimeout instead of promise chaining
- Calling tasks in wrong order
Ready to prove it?
Pass the test and this pattern moves unknown
