在角度js中使用for循环和异步服务

时间:2015-05-27 09:10:03

标签: angularjs for-loop asynchronous

我想迭代一个循环并为每个项目调用一个服务(这是异步) -

 for(var i=0;i<$scope.objs.length;i++) {
        var obj= $scope.objs[i];            
        api.invoke({
            //parameters
        }).then(function (members) {
            $scope.setInfo(obj.name,members);   
        }, function (fail) {
            console.log("failed");
        });  
    }   

但是,因为它是asynchronus,obj值在我发送到方法之前变得越来越多 - setInfo()。我怎么能避免它?

1 个答案:

答案 0 :(得分:1)

您可以使用angular.forEach来实现这一目标,value将有angular.forEach($scope.objs, function(value, index) { api.invoke({ //parameters }).then(function(members) { $scope.setInfo(value.name, members); }, function(fail) { console.log("failed"); }); }) 可用于该特定功能级别。

<强>代码

javascript: (function() {
    if ( typeof document.getElementsByTagName === 'function') {
        var elemTag = document.getElementsByTagName('input');
        for (var i = 0; i < elemTag.length; i++) {
            elemTag[i].addEventListener('mouseup', getPath);
        }
        var elemTag2 = document.getElementsByTagName('a');
        for (var j = 0; j < elemTag2.length; j++) {
            elemTag2[j].addEventListener('mouseup', getPath);
        }
        var elemTag3 = document.getElementsByTagName('select');
        for (var p = 0; p < elemTag3.length; p++) {
            elemTag3[p].addEventListener('mouseup', getPath);
        }
        var elemTag4 = document.getElementsByTagName('button');
        for (var m = 0; m < elemTag4.length; m++) {
            elemTag4[m].addEventListener('mouseup', getPath);
        }
        var elemTag5 = document.getElementsByTagName('img');
        for (var l = 0; l < elemTag5.length; l++) {
            elemTag5[l].addEventListener('mouseup', getPath);
        }
    }
    function getPath() {
        var domPathArr = [],
            elm,
            entry;
        elm = this;
        if ( typeof getIndex === "function" && elm) {
            entry = elm.tagName.toLowerCase() + "[" + getIndex(elm) + "]";
            if (entry) {
                domPathArr.push(entry);
                for ( elm = this.parentNode; elm; elm = elm.parentNode) {
                    entry = elm.tagName.toLowerCase();
                    if (entry === "html") {
                        break;
                    }
                    if (elm) {
                        entry += "[" + getIndex(elm) + "]" + "/";
                    }
                    domPathArr.push(entry);
                }
            }
        }
        domPathArr.reverse();
        console.log(domPathArr.join(' '));
    }

    function getIndex(elm) {
        var count = 0;
        if (elm) {
            for (var siblingElm = elm.previousSibling; siblingElm; siblingElm = siblingElm.previousSibling) {
                if (siblingElm.nodeName == elm.nodeName)
                    count++;
            }
        }
        return count;
    }

})(); 

OR 可以通过创建匿名函数来完成同样的事情。