Async function syntax in Javascript - Time & Space Complexity
We want to understand how the time it takes to run an async function changes as the input grows.
How does waiting for asynchronous tasks affect the total time?
Analyze the time complexity of the following code snippet.
async function fetchData(urls) {
const results = [];
for (const url of urls) {
const response = await fetch(url);
const data = await response.json();
results.push(data);
}
return results;
}
This function fetches data from a list of URLs one by one, waiting for each to finish before starting the next.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each URL and wait for its fetch to complete.
- How many times: Once for each URL in the input list.
Each URL causes a fetch that takes some time. Since the function waits for each fetch before starting the next, the total time adds up.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 fetches, done one after another |
| 100 | 100 fetches, each waited for in order |
| 1000 | 1000 fetches, all waited for sequentially |
Pattern observation: The total time grows roughly in direct proportion to the number of URLs.
Time Complexity: O(n)
This means the total time grows linearly with the number of URLs because each fetch waits for the previous one to finish.
[X] Wrong: "Async functions always run all tasks at the same time, so time does not grow with input size."
[OK] Correct: In this code, each fetch waits for the previous one to finish, so tasks run one after another, making total time grow with input size.
Understanding how async functions handle waiting helps you explain performance in real apps, showing you know how code runs over time.
What if we changed the code to start all fetches at once and then wait for all to finish? How would the time complexity change?