Sometimes, we want to run asynchronous process inside a JavaScript for loop.
In this article, we’ll look at how to run asynchronous process inside a JavaScript for loop.
How to run asynchronous process inside a JavaScript for loop?
To run asynchronous process inside a JavaScript for loop, we can use async an await.
For instance, we write
const func = async () => {
let i;
let j = 10;
for (i = 0; i < j; i++) {
await asycronouseProcess();
console.log(i);
}
};
to create the func
function that runs a for loop.
In it, we call asycronouseProcess
which is a function that returns a promise.
We use await
to wait for the promise to finish before continuing to the rest of the code in the loop.
Conclusion
To run asynchronous process inside a JavaScript for loop, we can use async an await.