Javascript : How to wait in for loop?
So finally you are in a situation where you want to do asynchronous task in a sequence inside a loop and you want to wait for the asynchronous task to complete it’s process and then move to next item in the list… right?
Great! Then you are on right page.
Let’s assume we have an array [1, 2, 3]
let myitems = [1, 2, 3];
And suppose we have to call one asynchronous function for each item which takes 3 seconds to process and respond.
So for that let us create one delay function with setTimeout which we will call inside our asynchronous function to create some delay in response.
function delay(){
return new Promise(){ resolve => setTimeout(resolve, 3000)
}
Then we will write our asynchronous function using async-await and call it itemRunner.
async function itemRunner(item){
await delay();
console.log(item);
}
Now if you try to use for loop on myitems array and call itemRunner, it will not wait itemRunners response. It will just call and move to next time and print 1,2,3 in console after three seconds.
But we don’t want this. We want to process the array in sequence and wait for the current item to finish it’s process and then move to next item. To achieve this we will need to wrap for..loop inside a async function and then we can make a use of await which will pause our loop and wait for promise to resolve. Once promise is resolved then it will move to the next item.
async function processTasks(array) {
array.forEach(async (item) => {
await itemRunner(item);
})
console.log('Completed!!!');
}
Above function will print each item after 3 seconds interval.
here is the full code snippet..
let myitems = [1, 2, 3];function delay(){
return new Promise(){ resolve => setTimeout(resolve, 3000)
}/* you actual processing function */
async function itemRunner(item){
await delay();
console.log(item);
}/* here is how you can wait in loop */
async function processTasks(array) {
array.forEach(async (item) => {
await itemRunner(item);
})
console.log('Completed!!!');
}processTasks(myitems);
That’s all!
Hope it helps. Thanks for reading.