Reputation: 847
Can someone please explain me why the below code prints "arg1 0" while I expect it to print "arg1 hi". Is it due to the lexical scope?
runIt();
function localScoped(arg1, callback) {
console.log('arg1', arg1);
callback();
}
function runIt() {
var myValue = 0;
async.eachLimit(["hi"], 1,
function launchOneVar(clientCode, doneLaunchOneVar) {
async.waterfall([
function (myCallback) {
myValue = clientCode;
myCallback();
},
async.apply(localScoped, myValue)
], function (err, result) {
console.log(myValue);
doneLaunchOneVar(null, result);
});
},
function finishing(err) {
}
);
}
Upvotes: 1
Views: 215
Reputation: 14992
Waterfall is just a function.
There is not any magic here.
Any function in Javascript must evaluate its arguments before call.
So, async.apply(localScoped, myValue)
evaluates before async.waterfall
and closured old myValue's value (0);
You can pass it through waterfall:
function (myCallback) {
myValue = clientCode;
myCallback(null , myValue);
},
async.apply(localScoped);
Or write a wrapper function, like:
function(next) {
localScoped(myValue, next);
}
Upvotes: 1
Reputation: 7896
try below solution:
runIt();
function localScoped(arg1, callback) {
console.log('arg1', arg1);
callback();
}
function runIt() {
var myValue = 0;
async.eachLimit(["hi"], 1,
function launchOneVar(clientCode, doneLaunchOneVar) {
//console.log(clientCode);
async.waterfall([
function (myCallback) {
myValue = clientCode;
myCallback(null , myValue);
},
async.apply(localScoped)
], function (err, result) {
console.log('last - '+myValue);
doneLaunchOneVar(null, result);
});
},
function finishing(err) {
}
);
}
how water fall works: .
Runs a list of async tasks, passing the results of each into the next one.
Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.
For more detail have a look at: https://www.npmjs.com/package/async-waterfall
Upvotes: 0