0

I have been trying to find a solution for this, and I've found similar things, but not exactly the same as this problem.

for (var i = 0; i < userArray.length; i++) {
        var username = userArray[i];
        var employee_id = $('#' + username + '_corresponding_employee_id').val();

        followUserBatch(user, username).done(function(data) {
            // How to get the correct value of username in here?
            outcomes.done.push(username);
        })
 }

Basically what ends up happening is that when I do outcomes.done.push(username);, username is always the last value of userArray.

dtgee
  • 1,272
  • 2
  • 15
  • 30

1 Answers1

4

You can use an IIFE to scope your variable properly:

for (var i = 0; i < userArray.length; i++) {
    var username = userArray[i];
    (function (inner_username) {
        var employee_id = $('#' + inner_username + '_corresponding_employee_id').val();

        followUserBatch(user, inner_username).done(function(data) {
            outcomes.done.push(inner_username);
        })
    })(username);
}

IIFE = Immediately Invoked Function Expression. You can pass-in a variable that will change at a later time, and its value will remain constant within the IIFE.

Here's some explanation of IIFE's: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Jasper
  • 75,717
  • 14
  • 151
  • 146