2017-05-30 270 views
1

我正在使用異步來執行第二個數據庫查詢。該查詢的結果必須作爲對象添加到第一個查詢中。如何等待異步完成 - NodeJs

問題是,當異步結束時,數據沒有改變,因爲他已經發送了未改變的數據。有沒有辦法等待異步完成?

我已經使用了超時,但數據的大小是未知的,所以這不是一個好的解決方案。

至今代碼:

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); 
     }); 
    }); 
    res.status(200); 
    res.send(rows); 
    } else { 
     DEBUG_WRITE('sensor','GET',404); 
     res.status(404); 
     res.send({status: "No entries found"}); 
    } 
}); 

回答

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是相同

+0

哇,那工作。謝謝,實際上這很容易。 – woutergoku