[英]Callback after ForEach (with async function inside) is done
我有一個帶有異步功能的.forEach循環,並且我的代碼在循環結束之前正在執行我的callback()。
有沒有一種方法可以使它完成循環,然后繼續執行我的callback()。
這是我的代碼:
var transactions = [];
t.transactions.forEach(function(id){
client.query('SELECT * FROM transactions WHERE id = $1;', [id], function(err, result) {
if(!err){
transactions.push({from : result.rows[0].from, to : result.rows[0].to, amount : result.rows[0].amount, time : result.rows[0].ct, message : result.rows[0].message, id : result.rows[0].id});
}
});
});
callback(transactions);
return done();
使用forEach的index參數測試您是否正在進行最后一個事務:
var transactions = [];
t.transactions.forEach(function(id, idx){
client.query('SELECT * FROM transactions WHERE id = $1;', [id], function(err, result) {
if(!err){
transactions.push({from : result.rows[0].from, to : result.rows[0].to, amount : result.rows[0].amount, time : result.rows[0].ct, message : result.rows[0].message, id : result.rows[0].id});
}
// If this is the last transaction, do the callback
if(idx === t.transactions.length - 1) callback(transactions);
});
});
由於每個事務只有一個查詢,因此可以將測試放入查詢的回調中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.