简体   繁体   中英

NodeJS mysql async queries

I have a question about async queries to DB in NodeJS and MySQL. Lets say I have the following code

var mysql = require("mysql");
var con = mysql.createConnection({
  ....
});

con.connect();    

con.query("select MILLIONS records from table1",function(err,rows){
    console.log('Data received 1');
});

con.query("select HUNDRED records from table2",function(err,rows){
    console.log('Data received 2');
});

first query takes much more time to be executed, second is much faster and I am expecting that second callback will be executed first, but its not :). I tried to create second connection and it worked as expected - calls worked asynchronously. Looks like connection is not shared between two separate async queries, they will run consequentially anyway. Or I am doing something wrong? Maybe someone could provide some information about how to do async calls without establishing connection for each call.

A connection represents a stream that sends commands to the server and receives data between your application and the server. When that stream is busy sending millions of records, it can't also be handling another query.

If you want to execute multiple queries in parallel, you will need multiple connections. You should consider using a connection pool for this.

var pool  = mysql.createPool({ ... });

pool.query("select MILLIONS records from table1",function(err,rows){
    console.log('Data received 1');
});

pool.query("select HUNDRED records from table2",function(err,rows){
    console.log('Data received 2');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM