Async Await for a loop within a loop

Hello, I have been hitting my head against the wall on this one. I am trying to use a for loop to console.log numbers with a setTimeout to create a delay effect.

This code works fine:

async function loop() {
        
                for (let i = 0; i < 2; i++) {
                        
                        await delay(i);
        
                }
        
        };

        function delay(i) {

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

                        console.log(i);
                        setTimeout(resolve, 1000);
                
                });

                        

        }

        loop();

^ So when I run this code I get:

0
1

logged into the console and each number shows 1000 milliseconds after the last. All well and good! BUT what I want to do is run a loop WITHIN a loop which is what is generating the delay.

I want the console to show this with 1 second delays between:

0,0
0,1
0,2
1,0
1,1
1,2

Here is what I have so far:

async function loop() {
        
                for (let i = 0; i < 2; i++) {
                        
                        await loop2(i);
        
                }
        
        };

        function loop2(i) {
                
                return new Promise(async (resolve, reject) => {
                
                        for (let i2 = 0; i2 < 3; i2++) {
                                
                                await delay(i, i2);
                
                        }

                });

        }

        function delay(i, i2) {
                
                return new Promise((resolve, reject) => {

                        console.log(i+','+i2);
                        setTimeout(resolve, 1000);
                        
                });

        }

        loop();

So, what happens when I run this code is that the first for loop is “blocked” after it runs through it’s first iteration. I don’t completely understand why the “await” is blocking the loop from completing. Could someone please help me?

Thanks so much in advance!

Hello, I found a solution to my problem! Here is the code that accomplishes exactly what I was going for:

async function task(i, j) {

          console.log(i+','+j);
          await timer(1000);
          
        }

        async function loop() {

          for(let i = 0; i < 2; i++) {

            for(let j = 0; j < 3; j++) {
                
                await task(i, j);

            }

          }

        }
            
        loop();

        function timer(ms) { return new Promise(res => setTimeout(res, ms)); }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.