Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 24, 2022 10:36 am GMT

How to use async/await inside for loop in JavaScript

There will be a time when you would want to run async operations inside for loops (ex. API calls).

In this article, we will discuss the possible approach to combine async/await and iterative logic. Lets take a look at how we can implement it in practice.

We are going to use - for await...of

Below is the code which shows how the API calls inside a for loop can be performed.

let urls = ["https://jsonplaceholder.typicode.com/todos/1","https://jsonplaceholder.typicode.com/todos/2"]async function makeAPICalls() {    for await(const url of urls){        console.log("Api call started for - ");        let result = await fetch(url).then(res=> res.json());        console.log("Result = ", result);        console.log("Api call ended for - ");    }}makeAPICalls();

Output

VM294:1 Api call started for - VM294:2 Promise{<pending>}VM294:5 Result =  {userId: 1, id: 1, title: 'delectus aut autem', completed: false}VM294:7 Api call ended for - VM294:3 Api call started for - VM294:5 Result =  {userId: 1, id: 2, title: 'quis ut nam facilis et officia qui', completed: false}VM294:7 Api call ended for - 

There are many better ways, this is just another example you may want to use.


Original Link: https://dev.to/rajeshroyal/how-to-use-asyncawait-inside-for-loop-in-javascript-4kh6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To