0

All:

I wonder how can I arrange $http request order and detect the finish point when all request finished, what I want to do is like:

Firstly init a request to get a json which include lots of images name and their url, then fetch them one by one( or together). When all image data ready, start to render the page to show all images.

Thanks

2 Answers 2

1

$http is a promise, and you can chain them. It could look like this :

$http.get('path').then(function (result){
    //do something with result
    return $http.get('path two');
}).then(function(result){
    //result is the resolve promise of $http.get('path two');
});

[EDIT]

I think I found something better in your case : $q.all

So you can iterate over an array of path, create promises, call the all and wait for them all to finish, I didn't try it but it should look like :

var list = ['path', 'path two'];
var promises = [];
for (var i = list.length - 1; i >= 0; i--) {
  promises.push($http.get(list[i]));
}; 

$q.all(promises).then(function(results){
  //results is an array, ordered like the promises array
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I am new to Promise, so you mean if I chain .then function, it will make it like asyn pattern? the second then() can be called only when the first $http.get('path two'); has result?
Thanks, so if I have a list of image URL, actually if I do not mind the order of the request but only care about if all requests have results, how can I do that?
I edited my answer, check the link, I think it's exactly what you need
0

if you want to make sure that no requests are going through, you could use this (useful for multiple requests):

$rootScope.isLoading = function () {
    return $http.pendingRequests.length > 0;
};

3 Comments

Thanks, I am wondering what is pendingRequests? Actually in my situation, I just give each img url in ne-repeat, the images request are handled by browser, I wonder how can I detect all images are loaded?
An array of objects that carry information about http requests that you make. If the array is bigger than 0, there are requests that were made, that have not yet returned.
Sorry, I did not quite catch this part, in my page, I use ng-repeat like <img ng-repeat="user in users track by $index" ng-src={{user.url}}/>, how can I related this with the Array you talk about, it seems that the browser handle the request?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.