Node.js mysql results to array
Map your array to promises, and then use Promise.all
. This also solves your unstated problem of closing your connection too early.
var mysql = require('mysql');var con = mysql.createConnection({ host: "10.0.1.103", user: "badayaba", password: "yadabuba", database: "xeroetc"});let wewant1 = ["invoices", "accounts", "items", "organisations", "receipts", "taxRates", "users", "trackingCategories"];function getmydata(sql, result, callback) { var query = con.query(sql); query.on('result', function(row) { callback(null, row); });};const promises = weweant1.map(it => { return new Promise((resolve, reject) => { getmydata(sql, it, function querydata(err, result) { if (err) { reject(err); } else { resolve(result); } }); })});Promise.all(promises) .then(results => { //results is a array of the resolved promises }) .catch(err => {}) .then(() => { // then after catch is a finally block con.end(); })
Of course you can also use async
/await
and get rid of the then
nesting. You can additionally promisify getmydata
. All use the same principle though: Wait on an array of promises.
Using async/await
If getmydata
returned a promise
or was declared async
, the following snippet would do, assuming it was in an async
function. So much cleaner...
const promises = weweant1.map(it => getmydata(sql, it))try { const results = await Promise.all(promises)} catch (e) { // handle error} finally { con.end();}