循环内asynchronous调用

可能重复:
在node.js中协调并行执行

首先,手上伪代码:

forEach(arrayelements) { asyncQueryFunction(function(qres) { //work with query results. }); } // finally, AFTER all callbacks did return: res.render("myview"); 

怎么做?

如果这还不够清楚,我会解释一下:

我需要做一系列的“更新”查询(在mongodb中,通过mongoose),循环的文档ID列表。 对于我的数组中的每个id我将调用一个asynchronous函数,将返回查询结果(我不需要做任何事情,实际上)。

我知道我必须使用.forEach() JavaScript循环,但是只有当我的所有asynchronous查询完成后,我怎样才能执行我的“最终”callback?

我已经使用优秀的asynchronous库( https://github.com/caolan/async )来实现这种任务,当我有一个“有限”的一系列任务执行。 但我不认为我可以通过它一系列不同的function。

我可以吗?

非常简单的模式是使用“运行任务”计数器:

 var numRunningQueries = 0 forEach(arrayelements) { ++numRunningQueries; asyncQueryFunction(function(qres) { //work with query results. --numRunningQueries; if (numRunningQueries === 0) { // finally, AFTER all callbacks did return: res.render("myview"); } }); } 

或者,也可以使用asynchronous辅助程序库(如Async.js)

如果我理解正确, asyncQueryFunction始终是相同的,因为在对每个文档应用相同的更新。

我使用一个辅助方法来保存后(只是交换更新)多个mongoose文件(从CoffeeScript转换,所以它可能不完美)callback:

 function saveAll(docs, callback) { // a count for completed operations, and save all errors var count = 0 , errors = []; if (docs.length === 0) { return callback(); } else { for (var i = 0; i < docs.length; i++) { // instead of save, do an update, or asyncQueryFunction docs[i].save(function(err) { // increase the count in each individual callback count++; // save any errors if (err != null) { errors.push(err); } // once all the individual operations have completed, // callback, including any errors if (count === docs.length) { return callback(errors); } }); } } }; saveAll(arrayElements, function(errors) { // finally, AFTER all callbacks did return: res.render("myview"); }