Javascript: Using Async/Await with Loops

Last updated on August 18, 2022 Snowball Loading... Post a comment

The demo program below shows you how to use the async/await syntax with a for loop in modern Javascript:

// kindacode.com
// create a promise that resolves after 1 second
const delayedFunction = (i) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(`Task ${i} finished`), 1000);
  });
};

// loop through an array with async/await
const run = async () => {
  const arr = [1, 2, 3, 4, 5];

  for (let e of arr) {
    console.log(`Task ${e} started`);
    console.log(await delayedFunction(e));
  }

  console.log('All tasks done!');
};

// run the program
run();

When running this program, you will see the tasks are executed sequentially one after another, and the time interval between the start and end of each task is 1 second:

Task 1 started
Task 1 finished
Task 2 started
Task 2 finished
Task 3 started
Task 3 finished
Task 4 started
Task 4 finished
Task 5 started
Task 5 finished
All tasks done!

That’s it. Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like