在我的代码中,我希望在返回结果之前执行数据库查询,因此将db.all
放在res.write
之前。我听说过async / await,您认为它适用于我的代码以确保在响应之前执行db请求吗?
app.use('/cart', function(req, res)
{
let item = JSON.parse(req.query.item);
let query = "select name from Product where id = ?";
db.all(query, [item.id], (err, rows) => {
if (err == null) {
if (rows.length != 0) {
let name = JSON.stringify(rows[0].name).replace(/['"]+/g, '');
item.name = name;
}
else {
item.name = 'Name not found';
}
}
else {
console.log(err);
}
});
if(item.qty <= 0){
cart.delete(item.id);
}
else{
cart.set(item.id, item);
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(Array.from(cart.values())));
console.log(Array.from(cart.values()));
res.end();
});