Await keyword behavior in Javascript - Time & Space Complexity
When using the await keyword, we want to understand how waiting for asynchronous tasks affects the total time a program takes.
We ask: How does the program's running time grow as we add more awaited tasks?
Analyze the time complexity of the following code snippet.
async function processTasks(tasks) {
for (const task of tasks) {
await task();
}
}
This code runs a list of asynchronous tasks one after another, waiting for each to finish before starting the next.
- Primary operation: Looping through each task and awaiting its completion.
- How many times: Once for each task in the input list.
Each task waits fully before the next starts, so total time adds up.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Wait for 10 tasks one by one |
| 100 | Wait for 100 tasks one by one |
| 1000 | Wait for 1000 tasks one by one |
Pattern observation: Total wait time grows directly with the number of tasks.
Time Complexity: O(n)
This means the total time grows in a straight line as you add more awaited tasks.
[X] Wrong: "Using await inside a loop runs all tasks at the same time, so time stays the same no matter how many tasks."
[OK] Correct: Actually, await pauses the loop until the current task finishes, so tasks run one after another, making total time add up.
Understanding how await affects timing helps you write efficient asynchronous code and explain your reasoning clearly in interviews.
What if we changed the loop to start all tasks without awaiting inside the loop, then awaited all at once? How would the time complexity change?
Practice
await keyword do in JavaScript?Solution
Step 1: Understand the role of
Theawaitawaitkeyword pauses the execution of an async function until the Promise it waits for settles (resolves or rejects).Step 2: Differentiate from other options
awaitdoes not make a function synchronous or create a Promise; it only pauses execution inside async functions.Final Answer:
Pauses the execution until a Promise resolves -> Option BQuick Check:
awaitpauses execution [OK]
- Thinking await makes functions synchronous
- Believing await creates Promises
- Using await outside async functions without error
await in JavaScript?Solution
Step 1: Check correct syntax for
The correct syntax placesawaitawaitbefore the Promise-returning function call, likeawait fetchData().Step 2: Identify invalid syntax
Options A, B, and C misuseawaitplacement, causing syntax errors.Final Answer:
const result = await fetchData(); -> Option DQuick Check:
awaitgoes before the Promise call [OK]
- Placing await after the function call
- Trying to declare variables with await keyword
- Adding await as a separate statement
async function test() {
const p = new Promise(resolve => setTimeout(() => resolve('Done'), 100));
const result = await p;
console.log(result);
}
test();Solution
Step 1: Understand the Promise and await
The Promise resolves after 100ms with the string 'Done'. Theawaitpauses until this resolution.Step 2: Check console.log output
After awaiting,resultholds 'Done', soconsole.log(result)prints 'Done'.Final Answer:
Done -> Option AQuick Check:
Await waits for Promise result [OK]
- Expecting Promise object instead of resolved value
- Confusing async function call with synchronous
- Thinking await causes errors outside async
function fetchData() {
return new Promise(resolve => setTimeout(() => resolve('Data'), 50));
}
const data = await fetchData();
console.log(data);Solution
Step 1: Check where await is used
awaitis used at the top level, outside any async function, which is not allowed in standard JavaScript.Step 2: Identify correct error cause
This causes a runtime syntax error becauseawaitmust be inside an async function.Final Answer:
Cannot use await outside async function -> Option CQuick Check:
Await only inside async functions [OK]
- Assuming await works globally
- Thinking async keyword is needed on fetchData only
- Believing Promise never resolves
async function getUserAndPosts() {
const user = await fetchUser();
const posts = fetchPosts(user.id);
return posts;
}Solution
Step 1: Analyze the sequence requirement
Posts must be fetched only after user data is ready, sofetchPostsmust wait foruser.Step 2: Check code for awaiting posts
Currently,fetchPostsis called withoutawait, so it returns a Promise immediately without waiting.Step 3: Correct usage
AddingawaitbeforefetchPostsensures posts are fetched after user data is available.Final Answer:
Add await before fetchPosts: const posts = await fetchPosts(user.id); -> Option AQuick Check:
Await each dependent async call [OK]
- Not awaiting dependent async calls
- Trying to run dependent calls in parallel
- Using Promise.all incorrectly for sequential tasks
Ready to prove it?
Pass the test and this pattern moves unknown
