1

I'm creating a while loop to cycle through an object array and depending on the info inside them, a MySQL transaction is executed. But, the conditional statement containing the MySQL transaction is not executed until the end of the while loop.

var objectArray = [ { id: 1, item: 4, rate: 1 }, { id: 2, item: 5, rate: 1 } ];
var d = 0;

while (d < objectArray.length) {
   var rate1 = objectArray[d].rate;
   console.log(objectArray[d].item);
   if (rate1 > 0.5) {
        console.log('step 1');
        // perform mysql transaction
   }
   d++;
}

The console logs show "4" and then "5" and then shows "step 1" twice. What it should show is "4" then "step 1" and then "5" then "step 1".

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
timyc
  • 35
  • 1
  • 4
  • Or, if the transaction returns a Promise, you can `await` each call of the Promise, see https://stackoverflow.com/questions/54584363/wait-in-for-loops-for-async-function – CertainPerformance Jun 21 '19 at 06:21
  • As mysql transaction is async task it will execute in background while your loop runs. So if you want it to be like it you should use promise or callback whatever suits you. – Dhaval Chaudhary Jun 21 '19 at 06:22

1 Answers1

0

var objectArray = [ { id: 1, item: 4, rate: 1 }, { id: 2, item: 5, rate: 1 } ];
var d = 0;

while (d < objectArray.length) {
   var rate1 = objectArray[d].rate;
   console.log(objectArray[d].item);
   if (parseFloat(rate1) > parseFloat(0.5)) {
        console.log('step 1');
        // perform mysql transaction
   }
   d++;
}