1

I have the following code in a function :

for (var key in handlers) {
  var handler = new handlerClass(key);
  handler.search(user.login, function(userFound) {
    if (!userFound) {
      handler.create... //Here handler is the last handler of the loop
    }
  });
}

I understand what appens, the loop finish before handler.create is called, so when it is called handler is equal to the last handler of the loop.

How can I solve this ?

IggY
  • 3,005
  • 4
  • 29
  • 54

1 Answers1

4

It is because of closure. Read about it here and here.

This should solve your issue.

for (var key in handlers) {
    var handler = new handlerClass(key);
    (function (handlerInstance) {
        handlerInstance.search(user.login, function (userFound) {
            if (!userFound) {
                // use handlerInstance here
            }
        });
    })(handler);
}
Community
  • 1
  • 1
Kunal Kapadia
  • 3,223
  • 2
  • 28
  • 36