By Muhammad Mudassir

2014-09-09 18:53:19 8 Comments

I making multiple mongoDB queries in loop. and want to send the all results as one data array.But when I simple use the return for send the data it simply return undefined and do not wait for results of all DB request. I also tried to use q.moulde but same issue.


var getPrayerInCat = function(data){
    var result ;
    var finalData = [];
    if(data.length >0){
                 var id=;
                     var deferred = Q.defer()
                     if (err) { // ...
                         console.log('An error has occurred');
                         // res.send(err);
                         result= finalData = err
                     } else {
                             // console.log('--0');
                             data2.prayersCount = 0;
                             result = deferred.resolve(finalData.push(data2))
                         } else {
                             // console.log('--'+prayer.length);
                             data2.prayersCount = prayer.length;
                             // console.log(prayer)
                             result =  deferred.resolve(finalData.push(data2))
                         } // else for data forward
                // deferred.resolve(finalData);

             /*if(finalData.length > 0) { return finalData;}*/

finalData is returned undefined.


@Bergi 2014-09-10 02:48:33

Let's start with the general rule for using promises:

Every function that does something asynchronous must return a promise

Which functions are these in your case? It's getPrayerInCat, the forEach callback, and Prayer.find.

Hm, Prayer.find doesn't return a promise, and it's a library function so we cannot modify it. Rule 2 comes into play:

Create an immediate wrapper for every function that doesn't

In our case that's easy with Q's node-interfacing helpers:

var find = Q.nbind(Prayer.find, Prayer);

Now we have only promises around, and do no more need any deferreds. Third rule comes into play:

Everything that does something with an async result goes into a .then callback

…and returns the result. Hell, that result can even be a promise if "something" was asynchronous! With this, we can write the complete callback function:

function getPrayerCount(data2) {
    var id =;
    return find({prayerCat:id})
//  ^^^^^^ Rule 1
    .then(function(prayer) {
//  ^^^^^ Rule 3
        if (!prayer)
            data2.prayersCount = 0;
            data2.prayersCount = prayer.length;
        return data2;
//      ^^^^^^ Rule 3b

Now, we have something a bit more complicated: a loop. Repeatedly calling getPrayerCount() will get us multiple promises, whose asynchronous tasks run in parallel and resolve in unknown order. We want to wait for all of them - i.e. get a promise that resolves with all results when each of the tasks has finished.

For such complicated tasks, don't try to come up with your own solution:

Check the API of your library

And there we find Q.all, which does exactly this. Writing getPrayerInCat is a breeze now:

function getPrayerInCat(data) {
    var promises =; // don't use forEach, we get something back
    return Q.all(promises);
//  ^^^^^^ Rule 1

If we needed to do anything with the array that Q.all resolves to, just apply Rule 3.

@Muhammad Mudassir 2014-09-10 14:50:28

I have used your code but same issue it return form find and donot wait for resukt from db . So the final result is undefined.

@Muhammad Mudassir 2014-09-10 14:50:50

getPrayerCat('').then(function(data){ getPrayerInCat(data) }).then(function(data2){ console.log(data2) }) var getPrayerInCat = function(data){ var result ; var finalData = []; if(data.length >0){ var promises =; return Q.all(promises); } }

@Muhammad Mudassir 2014-09-10 14:54:36

function getPrayerCount(data2) { var id =; return find({prayerCat:id}) .then(function(prayer) { if (!prayer) data2.prayersCount = 0; else data2.prayersCount = prayer.length; return data2; }); }

@Bergi 2014-09-10 14:54:55

You forgot about Rule 1 in your then callback. It needs to be getPrayerCat('').then(function(data){ return getPrayerInCat(data); }).then(…). Without returning anything, the promise resolves to undefined

@Muhammad Mudassir 2014-09-10 15:11:53

Thanks for the HElp @Bergi

@Muhammad Mudassir 2014-09-13 11:31:07

I again have same issue this time one more loop is added @Bergi

@Muhammad Mudassir 2014-09-13 11:34:16

findAllGroup(query).then(function(data){ return getmemberInfo(data) }).then(function(data2){ res.send(data2) }) var getmemberInfo = function(data){ var result ; var finalData = []; if(data.length >0){ var promises =; return Q.all(promises); } } function memberCount(data2) { var members = (data2.members).split(",");; if(members.length >0){ var promises2 =; return Q.all(promises2); } }

@Muhammad Mudassir 2014-09-13 11:34:55

function memberInfo(member){ var id = member return find({_id:member}) .then(function(User) { if (!User){ console.log(User)} else{ console.log(User)} return member; }); }

@Muhammad Mudassir 2014-09-13 11:35:52

var find = Q.nbind(User.findOne, User);

@Bergi 2014-09-13 17:40:33

I can't spot a mistake right away. If you still have an issue with it, you should ask a new question where you can format your code readably.

@Muhammad Mudassir 2014-09-14 13:19:06

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] How to retrieve POST query parameters?

39 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

5 Answered Questions

2 Answered Questions

[SOLVED] linking promises, or one promise triggers another

4 Answered Questions

[SOLVED] AngularJS : chaining http promises $q in a service

2 Answered Questions

[SOLVED] How to multi-callback a promise in AngularJs with $q?

1 Answered Questions

[SOLVED] How to download an xlsx in angular from express

1 Answered Questions

[SOLVED] mongodb 'sort' not working if 'limit' is removed

Sponsored Content