我已经为stormjs做了Nodejs: How to write high performance async loop,你可以查看stormjs serial loop demo
但是仍然存在并行循环的问题,例如我们有一个函数索引,它远程获取context‘http://host/post/{ requestContext(index, callback(err, context)) }’,我们需要获取[0-99]的context并按[context0...context99]的顺序将context推送到一个数组中
但是很明显,这个输出不能工作于stormjs parallel loop
我仍然想知道节点是如何完成这项任务的,但你必须让这些请求并行,而不是1乘1,它应该是并行请求和串行推送。
发布于 2011-05-22 02:41:47
var counter = 0;
// create an array with numbers 0 to 99.
_.range(0,100).forEach(function(key, value, arr) {
// for each of them request context
requestContext(key, function(err, context) {
// add the context to the array under the correct key
if (!err) {
arr[key] = context;
}
// increment counter, if all have finished then fire finished.
if (++counter === 100) {
finished(arr);
}
});
});
function finished(results) {
// do stuff
}不需要风暴。如果你想要一个执行/流程控制库,我会推荐Futures,因为它不会编译你的代码,而且“隐藏了魔力”。
以前,您通过递归遍历每个值,并按顺序执行它们,从而将它们按顺序推入数组。
这一次,您将并行执行它们,并告诉它们将数组中正确排序的键分配给它们自己的值。
_.range创建一个包含从0到99的值的数组。
https://stackoverflow.com/questions/6083420
复制相似问题