-1

I have tried to call a database operation from async for each loop. I have the following code

let succussCounter = 0;
let failureCounter = 0;

let mydata=[101,102,104,105];

myData.forEach(async data => {
          let response =
              await DbConnector.updateSampleTable(data);
          if(response){
            succussCounter ++;
          }else{
            failureCounter++;
          }
 });

      console.log('succussCounter = ' + succussCounter);
      console.log('failureCounter = ' + failureCounter);

I want to print the success count & failure count after completing the whole loop. But this always prints both are 0.

Abdul Manaf
  • 4,933
  • 8
  • 51
  • 95
  • 2
    `Array.prototype.forEach` is always synchronous. Your console.logs are always executed before the callbacks have completed. Use a good ol' `for` loop with `await` inside of it (sequential), or `Promise.all()` (parallel) – blex Jun 01 '21 at 20:21

1 Answers1

0

you need to learn a bit of await async.

forEach just isn't usable for your case because it is synchronous, it doesnt await anything. Therefore in your code console logs are run before the foreach has the time to run any query.

here is my favorite option : (it runs db queries sequentially)

for (let data of myData) {
          let response =
              await DbConnector.updateSampleTable(data);
          if(response){
            succussCounter ++;
          }else{
            failureCounter++;
          }
 }

console.log(...);

here is another option, it closer to your code but less readable in my opinion. But it has the advantage to run queries in parralel.

await Promises.all(myData.map(async data => {
          let response =
              await DbConnector.updateSampleTable(data);
          if(response){
            succussCounter ++;
          }else{
            failureCounter++;
          }
});
console.log(...);
Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18