SalmonKiller SalmonKiller - 3 months ago 18
Javascript Question

Node JS - mysql - querying inside of a callback of a query

I was wondering if it's possible to query the database inside of a callback of another query. So for example,

connection.connect();
connection.query(query, [param1, param2], function(err, rows, fields) {
// do something
connection.query(new_query, function(err, rows, fields) {
// do something else
});
});
connection.end();


I am getting a
Error: Cannot enqueue Query after invoking quit.
error on line 4 of this code. So I was wondering if this is possible at all.

Answer

Explanation of your problem:

js is executed line by line. In order, that would be:

  1. connection.connect()
  2. connection.query( params...) (async i/o, placing callbacks)
  3. connection.end()

Then, when a the query to the database is finished, the callback in 2. is executed, but the 3. was executed before, ending connection. So in that point in callback, you cant make another query, because the connection is closed.

Solution:

connection.end() should be inside the last nested query

Fixed code:

connection.connect();
connection.query(query, [param1, param2], function(err, rows, fields) {
    // do something
    connection.query(new_query, function(err, rows, fields) {
         // do something else
         connection.end();
    });
});
Comments