"Derive Tasks from an Array.map" does not seem to work
Closed this issue · 3 comments
Your basic example:
var waterfall = require('async-waterfall');
var myArray = [1,2,3];
waterfall(myArray.map(function (arrayItem) {
return function (lastItemResult, nextCallback) {
// same execution for each item in the array
var itemResult = arrayItem * lastItemResult;
// results carried along from each to the next
nextCallback(null, itemResult);
}}), function (err, result) {
// final callback
console.log(result);
});
Error:
nextCallback(null, itemResult);
^
TypeError: undefined is not a function
Yeah, it was really meant to be illustrative, but you're right, it ought to be a working example. The issue is that the first function is called without arguments (other than the callback). There are several ways to approach this, and I suppose I'll update the example with the simplest, which is to remove the function arguments and run the calculations on a variable declared outside the mapped closures.
Depending on the situation, other good approaches I can think of are to start off with an initializer function, or to duck-type the arguments within the mapped function.
I ended up putting in two examples - still illustrative, but hopefully a bit more helpful. Here's actually executable forms of the same examples similar to the mods you made:
var waterfall = require('async-waterfall');
var myArray = [1,2,3];
var myResult = 1;
waterfall(myArray.map(function (arrayItem) {
return function (nextCallback) {
myResult *= arrayItem;
nextCallback();
}}), function (err) {
console.log(myResult);
});
waterfall([function initializer (firstMapFunction) {
var initialValue = 1;
firstMapFunction(null, initialValue);
}].concat(myArray.map(function (arrayItem) {
return function (lastItemResult, nextCallback) {
var itemResult = arrayItem * lastItemResult;
nextCallback(null, itemResult);
}})), function (err, result) {
console.log(result);
});
thanks!