I am trying to insert several (hundres/thousands) of records to MySQL database. My problem is that I am not really sure what's the best way how do it. Example:
function saveData(data, callback) {
var dataLength = data.length,
saved = [];
for (var i = 0; i < dataLength; i++) {
db.query("INSERT INTO table VALUES (?, ?, ?)", data[i], function(err, res) {
if (err) {
// ...
}
saved.push(res.insertId);
});
}
}
The problem is that after all data is saved (save[] contains all IDs) I need to pass this array to a callback. Obviously I can't do it immediately... I have to wait for all queries to be done.
The questions: Should I use for loop or is it better to do it recursively (Next insert will be called after previous is done), should I check if saved.length === dataLength and then return the array or is there some better way how to do it?