Sumit Tiwari
Sumit Tiwari

Reputation: 139

Async Promises inside for loop inside for loop

var a = [1, 2, 3];
var b = [3, 4, 5];


for (var i = 0; i < a.length; i++) {
    console.log('value of i is ', i);
    for (var j = 0; j < b.length; j++) {
        console.log('value of j is ', j);
        here some blocking code like setTimeout or any database call
    }
}

I want this output

value of i is ',0
value of j is ',0
value of j is ',1
value of j is ',2
value of i is ',1
value of j is ',0
value of j is ',1
value of j is ',2

Upvotes: 0

Views: 36

Answers (1)

Batajus
Batajus

Reputation: 6257

You can use async and await to do that. Async/Await is working with promises:

var a = [1, 2, 3];
var b = [3, 4, 5];

async function asyncStuff(a, b) { 
    for (var i = 0; i < a.length; i++) {
        console.log('value of i is ', i);
        for (var j = 0; j < b.length; j++) {
            console.log('value of j is ', j);
            // Waits until the promise has resolved and continues the for-loop
            await someDatabaseCall();
        }
    }
}
// Call your function
asyncStuff(a, b);

Be aware that async/await does not block the execution of the Array.forEach.

Upvotes: 1

Related Questions