promise in forloop 1

promise in forloop

(async function loop() {
    for (let i = 0; i < 10; i++) {
        await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
        console.log(i);
    }
})();

Here is what the above code is Doing:
1. We create an async function called loop.
2. We create a for loop that will run 10 times.
3. Inside the for loop, we create a promise that will resolve after a random amount of time.
4. We await the promise.
5. We log the current value of i.
6. We call the loop function.

The output of the above code will be:
0
1
2
3
4
5
6
7
8
9

Similar Posts