我正在尝试在mysql数据库中插入几条记录,我需要获取每条记录的ID并将其发送回客户端。我正在使用的代码:
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);
});
问题在于.query方法似乎是异步的,并且在实际填充idArray之前执行以下代码:
console.log('array out of the loop: ' + idArray);
res.send(idArray);
什么是处理此问题的合适方法?