SalmonKiller
SalmonKiller

Reputation: 2203

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.

Upvotes: 2

Views: 2170

Answers (3)

Alex
Alex

Reputation: 838

i try to use for connection.release();

pool.getconnection(function(err,connection){
if(!err)
{
    connection.release();//after this perform query operation
    connection.query(query, [param1, param2], function(err, rows, fields) {
    // do something
       connection.query(new_query, function(err, rows, fields) {
         // do something else
       });
    });
}
})

Upvotes: 0

jperelli
jperelli

Reputation: 7197

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();
    });
});

Upvotes: 2

schtever
schtever

Reputation: 3250

Yes, you can issue queries in callback. You're getting the error because the connection.end call is NOT in a callback. Where you have it now, it will be called before the first callback fires.

Upvotes: 2

Related Questions