2013-11-25 211 views
0
data.forEach(function(shelf){ 
    books.find({"shelfid":shelf.id},function(book){ 
    //book1,book2,book3 
    }) 
}); 

每个书架都有一个ID,我找到所有具有这些ID的书籍。 因此,假设这种方法找到3本书,当foreach完成时,我该如何回应所有那些 书籍。foreach完成时做出响应

+0

我怎么知道,如果每个完成? – hackio

+2

如果你有几个异步方法,我建议使用[async.js](https://github.com/caolan/async)作为节点。 – adeneo

+1

你可以使用[promises](https://github.com/kriskowal/q) – katranci

回答

1

async module非常适合这样的:

它通过每一个迭代基本上并允许您指定要运行后,他们都运行的功能。

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

编辑

由于WiredPrairie指出,这样做更有意义:

books.find({shelfid: { $in: [shelfIds] }}, function(books){ 
    // do stuff with books. 
}) 
+0

不可能不使用模块吗? – hackio

+0

@hackio更新了答案,以包含一种无需模块的方式。 – Niall