tl;dr: What is the correct way to handle two or more asynchronous queries to a MySQL database using node-mysql with ExpressJS?
I am using ExpressJS with node-mysql to perform two separate, unrelated database queries on a MySQL database. Since the responses are asynchronous I am nesting the queries which means they end up happening one after the other.
This seems like an ugly, slow and generally bad approach, especially if I were to add a third or fourth query.
var mysql = require('mysql');
var credentials = {...}
router.get('/api/url/', function (req, res) {
return_data = {}
var connection = mysql.createConnection(credentials);
query1 = "SELECT column1 FROM table1 WHERE column2 = 'foo'";
query2 = "SELECT column1 FROM table2 WHERE column2 = 'bar'";
connection.query(query1, {}, function(err, results) {
return_data.table1 = results;
connection.query(query2, {}, function(err, results) {
return_data.table2 = results;
connection.end();
res.send(return_data);
});
});
});