如何在异步回调

时间:2015-11-06 19:30:06

标签: javascript variables asynchronous callback anonymous-function

我有这个for循环:

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;
   });
}

由于charService.get()是异步的,所以在执行回调时,character是数组的最后一个元素(因为循环已经结束),因此所有以前的character都是单独留下没有数据。

如何保证回调中的character.data引用异步方法执行的循环的character

2 个答案:

答案 0 :(得分:1)

您可以将其包装成功能

Class1 c = TempData["class1"] as Class1;

答案 1 :(得分:0)

尝试在Function.prototype.bind()功能使用.then(),设置为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));
}