An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
May 24, 2022 10:36 am GMT
Original Link: https://dev.to/rajeshroyal/how-to-use-asyncawait-inside-for-loop-in-javascript-4kh6
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To