How to perform Synchronous Programming

Viewed 48

I am not a native English speaker, so please ignore my mistakes.

I am using NodeJs and want to insert bulk data into the MySQL database.

I have an insertion query inside a nested loop and want to use async-await in the insertion query in a nested loop to perform the synchronous insertion and wait till the loop completes.

for(i=0; i<100; i++){
    for(j=0; j<100; j++){
        // mysql insert query
    }
}
1 Answers

One way to do this is to push all promises(async calls) in an array using a loop and then use methods like Promise.all() or Promise.allSettled() to execute them all.

let promiseArr = [];
for (let i = 0; i < 5; i++) {
   promiseArr.push(asyncAction)
}
Promise.all(promiseArr).then((res => {
    // success case
}, err => {
    // error case
});

docs: Promise.all() Promise.settledAll()

Related