Search code examples
javascriptnode.jslexical-scope

Nodejs asyn.apply and Javascript Apply


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) {
     }
  );

}

Solution

  • 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);
    }