This is a great candidate for using async . Here you can reorganize this using it:
var mysql = require('mysql'); var async = require('async'); var credentials = {...} router.get('/api/url/', function (req, res) { var connection = mysql.createConnection(credentials); var query1 = "SELECT column1 FROM table1 WHERE column2 = 'foo'"; var query2 = "SELECT column1 FROM table2 WHERE column2 = 'bar'"; var return_data = {}; async.parallel([ function(parallel_done) { connection.query(query1, {}, function(err, results) { if (err) return parallel_done(err); return_data.table1 = results; parallel_done(); }); }, function(parallel_done) { connection.query(query2, {}, function(err, results) { if (err) return parallel_done(err); return_data.table2 = results; parallel_done(); }); } ], function(err) { if (err) console.log(err); connection.end(); res.send(return_data); }); });
Obviously, there are more elegant ways to do this, but it perfectly demonstrates the concepts. Two requests are executed in parallel, and then, once they are completed, we call the last function to close the connection and return the data.
If there is an error, we will immediately go to the last function and call it, which will probably lead to strange behavior when we send return_data anyway, so I would not recommend using this code as is.
If you want to know more, check out the asynchronous documentation .
remyp source share