0

The output of the below code is:

OuterQuery
OuterQuery
InnerQuery
InnerQuery
InnerQuery

I want the output to be

OuterQueryInnerQueryInnerQueryOuterQueryInnerQuery.

Why is it executing all outer blocks first in Node JS? Any Suggestions to make it execute them in order?

var new1 = function () {
  connection.query("select ID from tbl1", function (error, result, fields) {
    for (var id in result) {
      console.log("Outer Query");
      connection.query("select name from tbl2 where ID = '" + result[id].ID + "' ", function (err, result, fields) {
        if (err) throw err
        for (var count in result) {
          console.log("Inner Query");
        }
      })
    }
  })
}
export.new1 = new1;

Thanks.

Yodha
  • 45
  • 9
  • 3
    `Why is it executing all outer blocks first in Node JS?` because it's asynchronous. The queries are going to be resolved and the callback fired after the `for` loop finishes. – VLAZ May 18 '18 at 21:47
  • @vlaz Instead of just displaying, I am updating database values in the inner loop based on the outer loop result. I noticed that the code is taking the last value of outer loop and then it starts updating the db in the inner loop with same values. – Yodha May 18 '18 at 21:58

0 Answers0