I am trying to insert several records in a mysql database and I need to get each record's ID and send it back to the client. The code I'm using:
app.post('/saveLesson',function(req, res){
var idArray = [];
let sections = JSON.parse(req.body.sections);
for (let i = 0; i < sections.length; i++) {
let sql = 'INSERT INTO sections (title, content, duration) VALUES ("' + sections[i].title + '","' + sections[i].content + '","' + sections[i].duration + '");';
connection.query(sql,
function (error, result) {
if (error) throw error;
idArray.push(result.insertId);
console.log('array in the loop: ' + idArray);
}
);
}
console.log('array out of the loop: ' + idArray);
res.send(idArray);
});
The problem is that the .query method seems to be asynchronous and the following code is executed before the idArray is actually populated:
console.log('array out of the loop: ' + idArray);
res.send(idArray);
What would be the appropriate way to deal with this issue?