In this quick tutorial we will learn how to use async await with for loops in Javascript and Typescript using simple examples.

There are mainly three types of for loops in JavaScript:

  1. for loop: A for loop allows you to execute a block of code repeatedly for a specified number of times.
  2. for…in loop: A for/in loop allows you to iterate over the properties of an object, executing the loop body once for each property.
  3. for…of loop: A for/of loop allows you to iterate over the values of an iterable object, executing the loop body once for each value.

Consider the following object array. Suppose we want to iterate over the users array, run some time consuming task on each iteration before logging the user object to the console.

const users = [
    {
        id: 1,
        name: 'Alan',
    },
    {
        id: 2,
        name: 'Joel',
    },
    {
        id: 3,
        name: 'Triss',
    }
];

To use await in a for loop, you must mark the loop function as async, and then use await inside the loop to wait for each asynchronous operation to complete before moving on to the next iteration.

In the following example, the code is same for each type of the loops except the syntax of the loop method.

Async await with for loop

async function randomWait() {
    await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 100)));
    return;
}

async function printUser() {
    for(let i=0; i < users.length; i++) {
        // Wait for some time consuming task to finish
        await randomWait();
        console.log(users[i]);
    }
}

printUser();
OUTPUT: 
{ id: 1, name: 'Alan' }
{ id: 2, name: 'Joel' }
{ id: 3, name: 'Triss' }

Async await with for…in loop

async function printUser() {
    for(const index in users) {
        await randomWait();
        console.log(users[index]);
    }
}
OUTPUT: 
{ id: 1, name: 'Alan' }
{ id: 2, name: 'Joel' }
{ id: 3, name: 'Triss' }

Async await with for…of

async function printUser() {
    for(const user of users) {
        await randomWait();
        console.log(user);
    }
}
OUTPUT: 
{ id: 1, name: 'Alan' }
{ id: 2, name: 'Joel' }
{ id: 3, name: 'Triss' }

This code defines two async functions: randomWait() and printUser().

randomWait() uses the await keyword to pause execution for a random amount of time, chosen using Math.random() and setTimeout(). Once the timer expires, the Promise resolves and the function returns.

printUser() is an async function that iterates over an array called users. For each element of the array, it first calls randomWait() to simulate some time-consuming operation, then prints the element to the console using console.log().

In the result, you can see that the data is printed in the sequential order in each of the three for loops.

Caveats

Using await inside a loop can potentially slow down the loop significantly, especially if the operations being awaited are time-consuming. In some cases, it might be more efficient to use Promise.all() to run multiple promises in parallel rather than awaiting them one at a time in a loop.

Categorized in:

Tagged in:

,