hackio
hackio

Reputation: 796

Make response when foreach is finished

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.

Upvotes: 0

Views: 286

Answers (1)

Niall Paterson
Niall Paterson

Reputation: 3580

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.
 })

Upvotes: 1

Related Questions