0

I have this for loop:

for(var i = 0; i < characters.length; i++)
{
   var character = characters[i];
   charService.get(character.name).then(function (characterData)
   {
        //I want character to be captured here, i.e. the character in the current loop
        character.data = characterData;
   });
}

As charService.get() is asynchronous, by the time the callback is executed, character is the last element of the array (because the loop has ended), hence all the previous character are left alone with no data.

How can I guarantee that character.data inside the callback is referencing the character of the loop the asynchronous method was executed?

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • use iffy and passing parameters will make it persist it – sumeet kumar Nov 06 '15 at 19:33
  • This has been answered [here](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop), [here](http://stackoverflow.com/questions/4288759/asynchronous-for-cycle-in-javascript) and [here](http://stackoverflow.com/questions/21184340/async-for-loop-in-node-js). – roperzh Nov 06 '15 at 19:37

2 Answers2

1

You can wrap it into function

for(var i = 0; i < characters.length; i++)
{
   (function(character){
   charService.get(character.name).then(function (characterData)
   {
        //I want character to be captured here, i.e. the character in the current loop
        character.data = characterData;
   });
   })(characters[i]);
}
0

Try using Function.prototype.bind() at .then() function , set to character

for(var i = 0; i < characters.length; i++)
{
   var character = characters[i];
   charService.get(character.name).then(function (characterData)
   {
        //I want character to be captured here, i.e. the character in the current loop
        this.data = characterData;
   }.bind(character));
}
guest271314
  • 1
  • 15
  • 104
  • 177