Human Cyborg Relations Human Cyborg Relations - 23 days ago 4x
Node.js Question

How does async work in Express?

I found the following on the ExpressJS guide:

var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'dbuser',
password : 's3kreee7'


connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);


Isn't this supposed to be bad practice? The way I see it, it is possible for the connection to end before the query can be executed. Wouldn't that give an error?


As stated here :

  • Every method you invoke on a connection is queued and executed in sequence.

  • Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

So even though the call to the end() method can be made before the query has completed, it won't actually be executed until the query has finished executing.

This has to do more with the mysql package than NodeJS itself.