0
data.forEach(function(shelf){  
  books.find({"shelfid":shelf.id},function(book){
   //book1,book2,book3
  })
});

Each shelf has an id, and i find all books which has those id's. So assume that this method finds 3 books, how do i response all those books at the same time, when the foreach is completed.

hackio
  • 776
  • 2
  • 8
  • 18
  • how do i know if the for each is completed? – hackio Nov 25 '13 at 22:19
  • 2
    If you have several async methods, I'd suggest using [async.js](https://github.com/caolan/async) for node. – adeneo Nov 25 '13 at 22:20
  • 1
    You could use [promises](https://github.com/kriskowal/q) – katranci Nov 25 '13 at 22:20
  • Isn't there like a million such questions on SO already? http://stackoverflow.com/questions/10551499/simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript – freakish Nov 25 '13 at 22:22
  • You should be using the `$in` operator anyway if this is really mongo/mongoose ... `books.find({shelfid: { $in: [ shelfIds ] }}, function(...){})` – WiredPrairie Nov 25 '13 at 23:03

1 Answers1

1

The async module is perfect for this:

It basically iterates through each one and allows you specify a function to run after they are all run.

var arr = [];
async.each(data, function (fd, callback) {
    books.find({"shelfid":fd.id},function(book){
        arr.push(book);
        callback();
    });
}, function(err){
    // this runs once they've all been iterated through.
    // if any of the finds produced an error, err would equal that error
    // books are in the arr array now.
});

EDIT

As WiredPrairie points out, doing this makes more sense:

 books.find({shelfid: { $in: [shelfIds] }}, function(books){
     // do stuff with books.
 })
Niall Paterson
  • 3,580
  • 3
  • 29
  • 37