1

I'm using node async, and I'd like to pass a variable to the method that it uses within the second parameter... e.g:

  async.map(submissions, addScore, function(err, submissions) {
    if (submissions) {
      return submissions;
    }
  });

I want to pass userId along with addScore but am not sure how to do this.

addScore is my method that I call on every submission and it requires a userId.

bob_cobb
  • 2,229
  • 11
  • 49
  • 109

1 Answers1

5

You can use a closure to put the userId into the addScore function scope:

var createAddScore = function(userId){
    return function(val){
        // do something with userID and val
    }
}

then:

async.map(submissions, createAddScore(1), function(err, submissions) {
    if (submissions) {
        return submissions;
    }
});
Ryan Lynch
  • 7,676
  • 1
  • 24
  • 33
  • Not quite working for my case. I modified it a little bit, but I get undefined is not a function. If I take it out of the function closure, it won't even go into my addScore() function. http://pastebin.com/u4AMmSz3 Can you please explain what I am doing wrong? – bob_cobb May 08 '13 at 03:52
  • You need to make the `addScore` function the return value of the `createAddScore` function. That way, you call `createAddScore` passing a `userId`, returning an `addScore` function, and that `userId` is available to the returned function when it is called by async. See these questions for details about closure's and scope in javascript: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work http://stackoverflow.com/questions/2858340/javascript-inner-function-scope-chain – Ryan Lynch May 08 '13 at 04:01
  • Nice dude thanks. I realized that what was messing me up initially was the additional callback that `map` passes in as the second parameter... so I was doing `return function(submission)` instead of `return function(submission, fn)` within `createAddFunction`, so it wasn't doing it asynchronously thus finishing too soon. Thanks for the help. :) – bob_cobb May 08 '13 at 04:18
  • @bob_cobb could you post your final solution? I'm having a similar issue. – Shaun Jun 26 '15 at 19:29