Javascript: Using Async/Await with Loops

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:
- Javascript: Count the occurrences of each word in a string
- Javascript: 2 Ways to Find Min/Max Property of an Object
- Javascript: 3 Ways to Calculate the Sum of an Array
- 3 Ways to Reverse a Given String in Javascript
- Javascript: 5 ways to create a new array from an old array
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
0 Comments