I'm using mysql module in nodejs.
I want to do something like this, but the problem is that the callback of query is async and I can't fill the result array correctly.. How can I do? Thanks!
function fn(callback) {
client.query(
'SELECT * FROM imbarcazioni',
function select(err, ships) {
if(err) {
throw err;
}
ships.forEach(function(ship) {
client.query(
'SELECT * FROM storico_imbarcazioni WHERE id_imbarcazione=' + ship.id,
function select(err, hist) {
ship.history = hist;
}
);
});
callback(hist);
});
}
As usual, I recommend async for these kinds of things. Here, you could use async.map:
function selectHistory(ship, callback) {
client.query('SELECT * FROM storico_imbarcazioni WHERE id_imbarcazione = ?', [ship.id], function(err, history) {
if(err) return callback(err);
ship.history = history;
callback(null, ship);
});
}
client.query('SELECT * FROM imbarcazoni', function(err, ships) {
async.map(ships, selectHistory, function(err, ships) {
// ships is an array with each ship along with it's history
});
});
That said, for your particular example, I would rather use a JOIN
and handle it in SQL:
SELECT * FROM imbarcazioni
LEFT JOIN storico_imbarcazoni ON storico_imbarcazoni.id_imbarcazione = imbarcazioni.id