1
[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)
});

When client.fooBar is called, an asynchronous call is made and an event foo is emitted on client. If I only wanted to process one number at a time (don't move to 2 until 1 has been processed) what would the best way be to organize my code? This is node.js.

switz
  • 24,384
  • 25
  • 76
  • 101
  • possible duplicate of [Node.js: Best way to perform multiple async operations, then do something else?](http://stackoverflow.com/questions/26268651/node-js-best-way-to-perform-multiple-async-operations-then-do-something-else) – Mulan Jun 02 '15 at 04:22
  • is your client.on implemented in client side? or that is a callback that tells u that it has sent to the client? – Tim Jun 02 '15 at 04:25

1 Answers1

1

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!");
});
Mulan
  • 129,518
  • 31
  • 228
  • 259