Passing variable to promise in a loop

后端 未结 5 1185
一生所求
一生所求 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:07

    One way is to capture i in a closure :

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

    Another way would be to arrange for itemID to be repeated back as a property of r :

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

提交回复
热议问题