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?"