node.js - 等待查询结果
问题描述
我无法成功等待 sql 查询结果
这就是我的代码的样子
socket.on('new', async function(information) {
console.log("check no offer en cours");
var checkOffer = "SELECT COUNT(*) as total FROM app__offer WHERE status_id = 1 AND profile_id = " + user.idUser;
doInsert = false;
con.query(checkOffer, function(err, result) {
if (err) throw err;
console.log(result[0].total);
if (result[0].total == 0) {
console.log("can insert");
doInsert = true;
}
}).then(function() {
console.log(doInsert);
if (doInsert) {
console.log("create offer");
var sql = "INSERT INTO app__offer (createdAt,updatedAt, startAt, programmed, startLatitude, startLongitude, commune_id, point_id, status_id,device,profile_id) " +
"VALUES ('" + todayDateTime + "','" + todayDateTime + "','" + todayDateTime + "'," + false + "," + user.latitude + "," + user.longitude + "," + user.idCommuneDestination + "," + user.idPoint + "," + 1 + "," + 'device' + "," + user.idUser + ")";
console.log(sql);
con.query(sql, function(err, result) {
if (err) throw err;
socket.emit('new', result);
});
} else {
console.log("Cet user a déjà une offre en cours");
}
});
问题是 doInsert 日志在 canInsert 日志之前执行。
解决方案
我认为con.query()
接受回调并且“thennable”返回一个 Promise。
在大多数情况下,如果提供了回调,那将是结果的处理程序,并且不会传递给 Promise。
所以
con.query(query, () => {
// this code is executed when the query ends
}).then(() => {
// this code is executed when the promise attached to .then() is resolved
// in this case con.query() is instant resolved cause a callback parameter is given
})
解决方案是将所有内容放在回调中或全部放在承诺链中。
推荐阅读
- html - 如何让一个div在Vue中的另一个div中占据100%
- go - OBJ 渲染不正确的纹理坐标
- php - Laravel Auth 登录验证编辑
- swift - 访问变量输出完成块
- selenium - 如何查找包含一些字符串和一些不包含在 div 中的 xpath?(Xpath 不包含)
- python - Alexa 技能帐号关联
- c++ - Boost::UUID 设置具体值
- sql - 使用通配符从 bigquery 表中删除列名
- css - 如何与'writing-mode:sideways-lr'结合使用水平和垂直居中文本?
- android - Android Q Kotlin - API 29:检查图像是否存在