I would like to send http requests until one of them responds with error 404.
There are 21 pages and I have something like this:
_getAll = function () {
var promises = [];
var pages = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
angular.forEach(pages, function (page) {
var deffered = $q.defer();
$http({
url: 'http://api.tvmaze.com/shows?page=' + page,
method: 'GET'
}).
success(function (data) {
console.log("OK")
deffered.resolve(data);
}).
error(function (error) {
deffered.reject(error);
console.log(error.status);
});
promises.push(deffered.promise)
})
return $q.all(promises);
},
But if I try to get http://api.tvmaze.com/shows?page=22 it returns 404 error.
So is there an option to make http request until one of them returns 404. while looping or somehow else?
These calls are asynchronous so a while loop would try to make calls to 1000s of pages in just a couple ms before you'd even load the first page. You need to wait for each page to complete before loading the next page.
One way to do this is to make a function to get a page and trigger it with the next page number each time you successfully load a page. Once you hit an error trigger a final success callback and pass the data back.
_getAll = function(callback) {
var pageData=[];
function getPage(page) {
$http({
url: 'http://api.tvmaze.com/shows?page=' + page,
method: 'GET'
}).
success(function (data) {
pageData.push(data);
//get next page
getPage(page + 1);
console.log("OK")
}).
error(function (error) {
//Hit an error. All done. Trigger callback.
callback(pageData);
console.log(error.status);
});
}
//get first page
getPage(0);
}
//usage:
_getAll(function(data){
//this function will trigger once we get an error
//data will be an array of all of the pages data
console.log(data);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With