Fab*_* B. 9 asynchronous node.js express
可能重复:
在node.js中协调并行执行
首先,动手伪代码:
forEach(arrayelements) {
asyncQueryFunction(function(qres) {
//work with query results.
});
}
// finally, AFTER all callbacks did return:
res.render("myview");
Run Code Online (Sandbox Code Playgroud)
怎么做?
如果不够清楚,我会解释:
我需要执行一系列"更新"查询(在mongodb中,通过mongoose),循环遍历文档ID列表.对于我的数组中的每个id,我将调用一个异步函数,它将返回查询结果(实际上我不需要对它们做任何事情).
我知道我必须使用.forEach()javascript循环,但是只有在我的所有异步查询完成后才能执行我的"最终"回调?
我已经使用优秀的异步库(https://github.com/caolan/async)来实现这种任务,当我执行一系列"有限"任务时.但我不认为我可以传递一系列不同的功能.
我可以吗?
非常简单的模式是使用'running tasks'计数器:
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");
}
});
}
Run Code Online (Sandbox Code Playgroud)
或者,使用Async.js等异步帮助程序库
| 归档时间: |
|
| 查看次数: |
7969 次 |
| 最近记录: |