How to Use Await in For Loop in JavaScript
You can use
await inside a for loop by marking the function as async. This lets you pause the loop until each asynchronous operation finishes before moving to the next iteration.Syntax
Use await inside an async function with a for loop to wait for each asynchronous operation to complete before continuing.
async function: Declares the function as asynchronous.for (let item of items): Loops through each item.await asyncOperation(item): Waits for the async operation to finish before next iteration.
javascript
async function processItems(items) { for (let item of items) { const result = await asyncOperation(item); console.log(result); } } async function asyncOperation(value) { return new Promise(resolve => setTimeout(() => resolve(value * 2), 100)); }
Example
This example shows how to use await inside a for loop to process an array of numbers sequentially. Each number is doubled after a short delay, and the result is logged in order.
javascript
async function doubleNumbers(numbers) { for (const num of numbers) { const doubled = await delayDouble(num); console.log(doubled); } } function delayDouble(n) { return new Promise(resolve => { setTimeout(() => resolve(n * 2), 200); }); } const nums = [1, 2, 3]; doubleNumbers(nums);
Output
2
4
6
Common Pitfalls
One common mistake is using await inside Array.forEach(). This does not wait for promises properly and runs all iterations at once.
Instead, use a for loop or for...of loop to ensure sequential execution.
javascript
const items = [1, 2, 3]; // Wrong: await inside forEach does not wait items.forEach(async (item) => { const result = await delayDouble(item); console.log(result); }); // Right: use for...of loop async function process() { for (const item of items) { const result = await delayDouble(item); console.log(result); } } process(); function delayDouble(n) { return new Promise(resolve => setTimeout(() => resolve(n * 2), 100)); }
Output
2
4
6
Quick Reference
- Always declare the function containing
awaitasasync. - Use
fororfor...ofloops for sequential async operations. - Avoid
awaitinsideforEachas it does not wait properly. - Each
awaitpauses the loop until the promise resolves.
Key Takeaways
Use await inside async functions to pause for asynchronous operations.
For sequential async tasks, use for or for...of loops, not forEach.
Each await in the loop waits for the promise to resolve before continuing.
Avoid using await inside forEach because it does not wait as expected.