0

UPDATE - Solution: I was for looping instead should have used MongoDBs $in feature - details here

I have the following Q.all block:

Q.all([
   getFirstBlock(),
   getSecondBlock(),
])
.then(function(){
   getSecondBlockProcessed();
})
.then(function(){
   res.json(completeArray);
});

The problem I have is when I go into the final then block I notice that the function getSecondBlockProcessed has not been completed. Everything in the first Q.all is done. Why isn't that promise getting resolved?

And the method in question looks like:

var getSecondBlockProcessed = function() {
    return Q.promise(function(resolve, reject) {
      for (var i=0; i<mostInRegion.length; i++){
        Person.find(
          {_id: mostInRegion[i]['_id']},
          {question:1, country: 1},
          function(err, found) {
            mostInRegion2.push(found);
          })
      }
      resolve();
      });
}

Any help would be appreciated/what have i overlooked?

Thanks

Community
  • 1
  • 1
userMod2
  • 8,312
  • 13
  • 63
  • 115
  • You'll need to **`return`** `getSecondBlockProcessed();` if it is asynchronous and returns a promise! Or just do `.then(getSecondBlockProcessed)` – Bergi Feb 17 '16 at 19:22
  • You mean like: `.then(function(){ return getSecondBlockProcessed(); })` – userMod2 Feb 17 '16 at 19:37
  • @Bergi Tried that - didnt work. Could it be do to with teh fact i have a `find()` in for loop? p.s. I dont think this a duplicate question as mine has a different. – userMod2 Feb 17 '16 at 19:39
  • 1
    @Bergi so the issue is when the `resolve()` is placed after the for loop (where i want it to be) it doesnt return the promise. If i place within the loop it only gives me one result (after the first loop in). – userMod2 Feb 17 '16 at 19:50
  • @Bergi solved it - http://stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array. Please remove duplicate question as I'm updating my question – userMod2 Feb 17 '16 at 19:55
  • Oh, right, that's another issue. You should promisify `find`, and use `Promise.all` or `Promise.map` to wait for the results of the loop. I did reopen so that you can post your solution as an [answer](http://stackoverflow.com/help/self-answer) – Bergi Feb 17 '16 at 20:55

0 Answers0