首页 > 解决方案 > 等待查询结果

问题描述

我无法成功等待 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 日志之前执行。

标签: node.js

解决方案


我认为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
})

解决方案是将所有内容放在回调中全部放在承诺链中。


推荐阅读