我有这个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
?
答案 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));
}