-2
  • in a loop -
    1. get some data from mysql
    2. insert the data into specific array ( at the index of i)

but as you know, 'i' increases much earlier than I expected. I know it's a problem with a sync/async proplem of nodejs. I wanna change it into synchronous function, but it's too confusing maybe because it's my first time...

...
dbconn.pool.getConnection(function (err, conn) {

...

    for (var i = 0; i < search_result.length; i++) {
        console.log("1, i here : "+i)
        conn.query(sql_getId_and_count, [search_result[i].address], function (err, result) {

              console.log("2.i here:" + i)
              if (err) console.error(err)
              else {
                   console.log("here : " + result[0].counter)
              }
        })
    }
})
Jerome
  • 734
  • 1
  • 8
  • 28
MJK
  • 5
  • 1
  • actually you don't need to make it synchronous thats not nodejs meant for, instead let it be asynchronous and I think you just want to access variable `i` inside query then please use `let` instead of `var`. – Vikash_Singh Jun 28 '19 at 06:30

1 Answers1

1

You can use while loop. Note that node.js is not made to interrupt the while loop.

You can also use process.nextTick(), and write the implementation inside it. eg : process.nextTick(function() {} )

Gopal Sharma
  • 755
  • 1
  • 12
  • 25