How can I make an Angular.forEach loop synchronous?

时间:2015-11-12 11:14:50

标签: angularjs

I am making a request to URLs in my forEach loop. I want the calls to be made synchronously...

angular.forEach(param, function(value) {
    FactoryWithURLCallingFunction.URLCallingFunction(param1, value, param3).success(function(data){
        console.log("Url returns: " + data);
        });
    });

Any help on this?

1 个答案:

答案 0 :(得分:3)

You should not make synchronous AJAX requests (although, it's possible), it's a sure way to making irresponsive UI. Instead, use proper promises capabilities:

$q.all(param.map(function(value) {
    return FactoryWithURLCallingFunction.URLCallingFunction(param1, value, param3).then(function (response) {
        console.log('Url returns:', response.data);
        return response.data;
    });
})).then(function(data) {
    console.log('All loaded:', data);
});