[1,2,3].map(function(num) {
client.fooBar(num);
// don't move on until `foo` is emitted to `client`
});
client.on('foo', function(num) {
console.log(num)
});
当client.fooBar
被调用时,一个异步调用被发起,并且在client
上发出一个事件foo
。如果我一次只想处理一个数字(在1
被处理之前不要移动到2
),组织代码的最佳方法是什么?这是node.js
。这是一个完全不同的问题(瑞士)。
不,这并没有完全不同。你有一个需要异步(事件驱动)控制结构的系列。
因为您的fooBar
函数触发foo
事件而不是接受回调,所以您需要将foo
事件侦听器附加到控制代码中,以通知循环何时继续到数组中的下一个元素。
除非有其他方法让控制结构知道何时进行,否则我看不出有其他方法可以完成你的任务。
使用async。每个系列来完成你的目标
async.eachSeries([1,2,3], function(num, done) {
client.once("foo", function() { done(); });
client.fooBar(num);
}, function(err) {
if (err) throw err;
console.log("all done!");
});
如果您不想依赖async
库,您可以编写自己的asyncForEach
函数
function asyncForEach(arr, iterator, callback) {
var queue = arr.slice(0);
function next(err) {
if (err) return callback(err);
if (queue.length === 0) return callback(null);
iterator(queue.shift(), next);
}
next();
}
然后在你的代码中使用
asyncForEach([1,2,3], function(num, done) {
client.once("foo", function() { done(); });
client.fooBar(num);
}, function(err) {
if (err) throw err;
console.log("all done!");
});