javascript - Issue in returning data retrieved from DB queries called in the loop -
i making multiple mongodb queries in loop. , want send results 1 data array.but when simple use return send data return undefined , not wait results of db request. tried use q.moulde same issue.
code:
var getprayerincat = function(data){ var result ; var finaldata = []; if(data.length >0){ data.foreach(function(data2){ var id= data2.id; prayer.find({prayercat:id},function(err,prayer){ var deferred = q.defer() if (err) { // ... console.log('an error has occurred'); // res.send(err); result= finaldata = err } else { if(!prayer){ // console.log(data2.id+'--0'); data2.prayerscount = 0; result = deferred.resolve(finaldata.push(data2)) } else { // console.log(data2.id+'--'+prayer.length); data2.prayerscount = prayer.length; // console.log(prayer) result = deferred.resolve(finaldata.push(data2)) } // else data forward } deferred.promise; }) // deferred.resolve(finaldata); }) /*if(finaldata.length > 0) { return finaldata;}*/ } } finaldata returned undefined.
let's start general rule using promises:
every function asynchronous must return promise
which functions these in case? it's getprayerincat, foreach callback, , prayer.find.
hm, prayer.find doesn't return promise, , it's library function cannot modify it. rule 2 comes play:
create immediate wrapper every function doesn't
in our case that's easy q's node-interfacing helpers:
var find = q.nbind(prayer.find, prayer); now have promises around, , no more need deferreds. third rule comes play:
everything async result goes
.thencallback
…and returns result. hell, result can promise if "something" asynchronous! this, can write complete callback function:
function getprayercount(data2) { var id = data2.id; return find({prayercat:id}) // ^^^^^^ rule 1 .then(function(prayer) { // ^^^^^ rule 3 if (!prayer) data2.prayerscount = 0; else data2.prayerscount = prayer.length; return data2; // ^^^^^^ rule 3b }); } now, have bit more complicated: loop. repeatedly calling getprayercount() multiple promises, asynchronous tasks run in parallel , resolve in unknown order. want wait of them - i.e. promise resolves results when each of tasks has finished.
for such complicated tasks, don't try come own solution:
check api of library
and there find q.all, this. writing getprayerincat breeze now:
function getprayerincat(data) { var promises = data.map(getprayercount); // don't use foreach, return q.all(promises); // ^^^^^^ rule 1 } if needed array q.all resolves to, apply rule 3.
Comments
Post a Comment