2014-03-24 107 views
1

我有一個.forEach循環,裏面有一個異步函數,我的代碼在循環結束前執行我的回調函數()。
有沒有辦法讓它完成循環,然後繼續我的回調()。
這裏是我的代碼:ForEach(內部具有異步函數)後的回調已完成

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(); 

回答

1

使用的forEach指標參數進行測試,如果你的最後一個交易:

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); 
    }); 
}); 

因爲你只得到了每個事務查詢,可以將測試放入查詢的回調中。

+0

非常感謝您的支持!對不起,我遲到了2天。 – C1D

相關問題