German Bernhardt
German Bernhardt

Reputation: 21

Node.js does not wait for the MySQL server sends the answer, and continues to work asynchronously

Print haphazardly and not wait for MySQL send a reply.

var mysql=require('mysql').createConnection({
 host:'localhost',user:'root',password:'',database:'dbname',port:3306
});
mysql.connect(function(error){if(error){throw error;}else{console.log('MYSQL SERVER [OK]');}});

console.log('// INI //');

var sql='SELECT * FROM sys_users';
mysql.query(sql,function(error,rows){
 if(!error){
  for(i=0;i<rows.length;i++){
   if(i<rows.length-1)
    console.log(rows[i].username);
   else console.log(rows[i].username);
  }
 }else console.log('Error');
});

console.log('// END //');

mysql.end();

would have to print:

  1. MYSQL SERVER [OK]
  2. // INI //
  3. List item
  4. // END //

but nevertheless printed:

  1. // INI //
  2. // END //
  3. MYSQL SERVER [OK]
  4. List item

Upvotes: 1

Views: 104

Answers (1)

jedrzejginter
jedrzejginter

Reputation: 412

That's the nature of Node.js - callbacks and async code processing. If you want to run come code after the database response will be returned, place that code inside the callback:

mysql.query(sql,function(error,rows){
   if (!error){
       for(i=0;i<rows.length;i++){
           if(i<rows.length-1)
               console.log(rows[i].username);
           else
               console.log(rows[i].username);
       }
   } else {
       console.log('Error');
   }

   /* Code to run. Move it to first `if`, if you want to run it only, when no error will occur. */
   console.log('//END //');

});

mysql.end();

Upvotes: 1

Related Questions