user6607973 user6607973 - 2 months ago 7x
MySQL Question

nodejs execute order using mysql

conn = mysql.createConnection(options);
var sql = 'select * from member';

for(var i=0; i<3; i++){
conn.query(sql, function(err,result){
for (var i=0; i<2; i++){

I'm using npm-mysql.
I expected the console would display '012qqq01', but actually I got '01201qqq'.
I'm confused. Why is 'conn.querry' executed last? Thank you in advance.


You have a function which logs i and then sends the queries to the database in a loop, and the logs through another loop. That function runs.

Either while that is going on, or sometime after it has finished, the results of the queries will be sent back from the database.

When the JS engine isn't busy running the first function, it will start checking to see if the event indicating a response from the database has arrived. Then it will call the callback function and log 'q'.