-1

I'm trying to pass current value to callback function. I used this answers to work with, but it doesn't work for me.

for (var i = 0; i < 4; i++) {
  (function(_i) {
    var options = {
        //Options here
    };
    console.log(_i); // 0, 1, 2, 3

    LocalImageManager.download(options, function (results, _i) {
      console.log(_i);  //undefined, undefined, undefined, undefined

      //Do stuff with results
    });

  }
})(i);

The problem is function always works with "i" variable, which is undefined after the loop finished.

Community
  • 1
  • 1
mordecai
  • 55
  • 9

2 Answers2

0
for (var i = 0; i < 4; i++) {
  (function(_i) {
    var options = {
      //Options here
    };
    console.log(_i); // 0, 1, 2, 3

    LocalImageManager.download(options, function (results) {
      console.log(_i); // 0, 1, 2, 3

      //Do stuff with results
    });
  })(i);
}
Abhi
  • 1,624
  • 2
  • 16
  • 29
-1

You need to change the definition of LocalImageManager.download because your callback method is calling from there only. You can send the value of _i in different parameter or with options you passed in function and use at the time of calling the callback method.

Liam
  • 27,717
  • 28
  • 128
  • 190
Anuj Kumar
  • 136
  • 6