[英]node.js + for loop + query execution
我正在執行for循環,在for循環中我正在執行postgresql查詢並將結果填充到數組中。 但我無法預測執行流程。
我的代碼:
var array =[];
for(var i = 0 ; i< latitude.length; i++){
client.query("SELECT value->>'xxxx' as xxxx_details FROM yyyyy WHERE ST_DWithin(ST_GeogFromText('SRID=4326;POINT ("+latitude[i]+" "+longitude[i]+")'), geography(the_geom), " + radius + ")", function(err, row, fields) {
array.push(row.rows[0]);
}
console.log("bbbbbbbbb=" +array);
我需要的是我希望在for循環中執行的所有查詢之后打印數組。 但現在它在陣列之前的打印已經填充。 幫我解決這個問題。 提前致謝..
原因是client.query是異步的,結果僅在回調中可用。
一個選項是async.js。 好寫什么時候用這里的東西 。
從該文章中,您可以為集合中的每個項目執行代碼。 因此,對於您的示例,您可以使用索引或foreach數組來構建一個sql查詢語句數組,然后為每個查詢執行一些操作。
如果查詢是一個查詢數組,那么類似於:
async.forEach(queries, function(query, callback) {
client.query(query, function(err, row, fields){
array.push(row.rows[0]);
callback(); // this signals async that you're done with this item
});
}, function(err) {
if (err) return next(err);
// all queries are done here
});
注意還有forLachLimit用於並行執行n和forEachSeries,其限制為1(順序)。
編輯:
更好的選擇是async / await,如果你使用typescript並編譯成ES6 +並使用node 4+(有生成器),現在可以使用async / await。
我在這個理智的節點回購中介紹了細節
來自該repo的片段顯示在循環中等待異步調用。 它保持異步,並且在完成之前不會進入下一行。 這也有你想象的try / catch處理的好處。
// await allows us to write linear code.
// makes it easy to also call async code in a loop
// offers easy error handling with try catch
var quotes: IQuote[];
var tries: number = 0;
while (true) {
try {
++tries;
// ASYNC/AWAIT
quotes = await this._store.find<IQuote>({});
break;
}
catch (err) {
if (tries == 3) { throw err; }
}
}
return quotes;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.