Passing variable to promise in a loop

后端 未结 5 1179
一生所求
一生所求 2021-01-30 05:40

I have a promise in a loop, and I don\'t know how to pass some scope variables into the promise handler.

for(var i in superarray){
    MyService.get(superarray[i         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 06:12

    By the time your callback is run, i will refer to the last element in your array. You can use a closure and capture the current value of i:

    for (var i in superarray){
        (function(j) {
            MyService.get(superarray[j].externalID).then(function(r) {
                console.debug(j);
            });
        })(i);
    }
    

提交回复
热议问题