如何等待异步完成 - NodeJs

时间:2017-05-30 13:54:01

标签: sql node.js asynchronous

我使用异步来执行第二次数据库查询。必须将该查询的结果作为对象添加到第一个查询中。

问题是当异步完成时,数据没有改变,因为他已经发送了未改变的数据。有没有办法等待异步完成?

我使用了超时,但数据的大小未知,因此这不是一个好的解决方案。

到目前为止的代码:

Integer

1 个答案:

答案 0 :(得分:1)

eachSeries采用的功能基本上是"我已完成"功能:

connection.query('SELECT * FROM SENSORS', function(err,rows) {
   if(rows.length !== 0) {
    DEBUG_WRITE('sensor/','GET',200);

    async.eachSeries(rows, function(row, callback) {
     connection.query('SELECT * FROM LOCATIONS WHERE LocationID=?',row.LocationID, function (error, result) {
        row.location = result; 
            callback(null,rows);
        });
    }, function(err){ //treat this as "i'm done iterating"

       // if any of the iterations produced an error, err will equal that error
      if(err) {
        //do something with the error
        res.status(500);
        return res.send(err);
      }

      res.status(200);
      return res.send(rows);
    });
   } else {
       DEBUG_WRITE('sensor','GET',404);
       res.status(404);
       res.send({status: "No entries found"});
   }
});

See here - 它与each相同,因此function是相同的

相关问题