通过 javascript 中的事件控制流程代码
Control flow code through an event in javascript
[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。
No. That's an entirely different question (switz).
不,一点也不完全不同。您有一个系列需要围绕它的异步(事件驱动)控制结构。
因为您的 fooBar
函数触发 foo
事件而不是回调,您需要将 foo
事件侦听器附加到控制代码以通知循环何时继续到数组中的下一个元素。
除非有其他方法让控制结构知道何时继续,否则我看不出有其他方法可以完成您的任务。
这需要 async.eachSeries 来实现您的目标
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!");
});
[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。
No. That's an entirely different question (switz).
不,一点也不完全不同。您有一个系列需要围绕它的异步(事件驱动)控制结构。
因为您的 fooBar
函数触发 foo
事件而不是回调,您需要将 foo
事件侦听器附加到控制代码以通知循环何时继续到数组中的下一个元素。
除非有其他方法让控制结构知道何时继续,否则我看不出有其他方法可以完成您的任务。
这需要 async.eachSeries 来实现您的目标
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!");
});