How to run functions iteratively with async await in JavaScript?

Running functions iteratively with async/await allows you to execute asynchronous operations in sequence within loops. This is useful when you need to process items one by one rather than concurrently.

Basic Syntax

async function iterativeFunction() {
    for (let i = 0; i 

Example: Sequential Function Calls

async function test(i) {
    while (i 

Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()
Call Demo1()
Call Demo2()

Example: Processing Array Items

async function processItems(items) {
    for (const item of items) {
        await processItem(item);
    }
    console.log("All items processed");
}

async function processItem(item) {
    // Simulate async operation with setTimeout
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(`Processed: ${item}`);
            resolve();
        }, 100);
    });
}

const items = ['apple', 'banana', 'cherry'];
processItems(items);
Processed: apple
Processed: banana
Processed: cherry
All items processed

Key Points

Using await in loops ensures sequential execution. Each iteration waits for the previous async operation to complete before continuing. This is different from concurrent execution where all operations start simultaneously.

Comparison: Sequential vs Concurrent

Approach Execution Use Case
Sequential (await in loop) One by one Order matters, rate limiting
Concurrent (Promise.all) All at once Independent operations, faster

Conclusion

Use async/await in loops for sequential processing when order matters or you need to avoid overwhelming resources. This pattern ensures each operation completes before the next one begins.

Updated on: 2026-03-15T23:18:59+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements