传递变量在循环中保证 [英] Passing variable to promise in a loop

查看:150
本文介绍了传递变量在循环中保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环的承诺,我不知道如何在一定范围变量传递到承诺处理。

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].externalID).then(function(r){
        console.debug(i);
});

为MyService是一个工作服务,以get方法返回一个承诺。

MyService is a working service, with a get method that return a promise.

app.factory('MyService', function($http,$q) {
  return {
     get : function(itemID){
        var deferred = $q.defer();
        $http.get('/someresturl/'+itemID).then(function(e) { 
                deferred.resolve(e.data);
        }, function(reason) {
                deferred.reject(reason);
        });
        return deferred.promise;
    }
});

在我的控制台中,console.debug logicaly不显示1,2,3,4,5。但是5,5,5,5,5。 (有我的superarray 5元)。

In my console, the console.debug logicaly doesn't display 1,2,3,4,5. But 5,5,5,5,5. (there are 5 elements in my superarray).

如何传递在我的承诺​​范围的'我'的价值,这样我就可以在然后用它()?

How can I pass 'i' value in my promise scope, so I can use it in the then() ?

这可能吗?

推荐答案

的一种方法是捕捉到 I 在封闭:

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

另一种方法是为 ITEMID 安排反复回为研究的属性:

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

这篇关于传递变量在循环中保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆