我怎么知道我的所有$ http GET请求都已完成?

时间:2022-05-30 07:27:42

Using AngularJs 1.6.5 I am making multiple $http GET calls using the for loop. Here is the code:-

使用AngularJs 1.6.5我使用for循环进行多个$ http GET调用。这是代码: -

for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    $http.get(url).then(successCallback, errorCallback);    
    function successCallback(response){
        console.log(response);
    };
    function errorCallback(error){
        console.log(error);
    };
};

What I want to do is trigger a function when all the GET requests are completed.

我想要做的是在完成所有GET请求时触发一个函数。

I referred to answer posted here and want to know how can this be done on an array as in my case?

我在这里提到了答案,并想知道如何在我的情况下在阵列上完成这个?

1 个解决方案

#1


6  

The time will likely arise where you need to resolve multiple promises at once, this is easily achieved through $q.all() by passing in either an Array or Object of promises which will call .then() once both are resolved:

你需要一次解决多个promises的时候可能会出现这种情况,这很容易通过$ q.all()传递一个Array或Object of promises来解决.then()一旦解决了这两个:

You can take an array and push your http calls into it

你可以拿一个数组并将你的http调用推入其中

var array  = [];
for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    array.push($http.get(url))
};

$q.all(array).then(function(response) {
     console.log(response)
}).catch(function(error){
    console.log(error)
});

Using this code, the response will come once all your requests are successful.

使用此代码,只要您的所有请求都成功,响应就会响起。

Here is an example documentation

这是一个示例文档

#1


6  

The time will likely arise where you need to resolve multiple promises at once, this is easily achieved through $q.all() by passing in either an Array or Object of promises which will call .then() once both are resolved:

你需要一次解决多个promises的时候可能会出现这种情况,这很容易通过$ q.all()传递一个Array或Object of promises来解决.then()一旦解决了这两个:

You can take an array and push your http calls into it

你可以拿一个数组并将你的http调用推入其中

var array  = [];
for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    array.push($http.get(url))
};

$q.all(array).then(function(response) {
     console.log(response)
}).catch(function(error){
    console.log(error)
});

Using this code, the response will come once all your requests are successful.

使用此代码,只要您的所有请求都成功,响应就会响起。

Here is an example documentation

这是一个示例文档