等待查询结果

时间:2019-05-28 15:54:21

标签: 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日志之前执行。

2 个答案:

答案 0 :(得分:1)

我认为con.query()接受回调,并且也是“可退回”的承诺。

在大多数情况下,如果提供了回调,它将作为结果的处理程序,并且不会传递给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
})

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

答案 1 :(得分:1)

我想要:-

try{
  let result = await con.query(checkOffer);
    if (result) {
      let resultFromAnotherQuery = await con.query(sql);
      if (resultFromAnotherQuery){
        console.log("done");
      }
    }
}catch(err) {
   console.log(err);
}