javascript - Callback after ForEach (with async function inside) is done -


i have .foreach loop async function inside of , code executing callback() before loop finished.
there way make finish loop , move on callback().
here code:

var transactions = []; t.transactions.foreach(function(id){     client.query('select * transactions id = $1;', [id], function(err, result) {         if(!err){             transactions.push({from : result.rows[0].from, : 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(); 

use index parameter of foreach test if you're on last transaction:

var transactions = []; t.transactions.foreach(function(id, idx){     client.query('select * transactions id = $1;', [id], function(err, result) {         if(!err){             transactions.push({from : result.rows[0].from, : 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 last transaction, callback         if(idx === t.transactions.length - 1) callback(transactions);     }); }); 

since you've got 1 query per transaction, can put test inside query's callback.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -