No. That's an entirely different question (switz).
No, it's not entirely different at all. You have a series that needs an asynchronous (event-driven) control structure around it.
Because your fooBar
function fires a foo
event rather than taking a callback, you need to attach a foo
event listener to the control code to notify the loop when to proceed to the next element in the array.
Unless there's some other way of letting the control structure know when to proceed, I don't see another way of accomplishing your task.
This uses async.eachSeries to accomplish your goal
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!");
});
If you don't want to depend on the async
lib, you can write your own asyncForEach
function
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();
}
Then use it in your code
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!");
});