taufique
taufique

Reputation: 2751

async.waterfall like alternative for async.eachSeries

I have to write some code snippet in node.js where I need to control the asynchronous flow with async.js. There is a function in async.js called async.waterfall which gives opportunity to pass some value to next executing function. My problem is I have to run async.eachSeries for controlling the flow over an array, but I can't find any option to pass some value like waterfall. Is there any?

Upvotes: 0

Views: 697

Answers (1)

Ben
Ben

Reputation: 5074

async.eachSeries() doesn't have option to pass on the value but you can you use closure to save the value for the next iteration. For example:

var async = require('async');

(function() {
  var lastValue = 1;

  async.eachSeries([1, 2, 3, 4, 5], function (item, eachCb) {
    console.log('item ' + item + ', last value: ' + lastValue);
    lastValue = lastValue + item;
    eachCb(null);
  }, function (err) {
    console.log('done:' + lastValue);
  });
})();

The output would be:

item 1, last value: 1
item 2, last value: 2
item 3, last value: 4
item 4, last value: 7
item 5, last value: 11
done: 16

As you can see in the output, the current iteration is using the last iteration's saved value.

Upvotes: 1

Related Questions