Search This Blog

2021/01/10

Synchronous For loop :

Loop can be made to wait until promise resolve which is put inside settimeout so as to wait for 2000 milliseconds.Each array item is printed after 2000 milliseconds delay.


let arr =[10,20,30,40,50,60,70,80,90]


runLoop = async ()=>{

for(let i=0;i < arr.length ;i++)

{

await new Promise((resolve,reject)=>{

setTimeout(function(){

resolve()

console.log(arr[i]);

}, 2000);

})

}

}


runLoop();


Output:

sangram@sangram-HP-Laptop-15-bs0xx:~/projects/nodejs/promise-all$ node loop.js

10

20

30

40

50

60

70

80

90


Here 10,20,30 ... these are printed after waiting for 2000 milliseconds for each iteration.

No comments:

Post a Comment