Reputation: 2352
I'm trying to fetch data via post request and the API I'm querying from returns a maximal 50 elements. This worked great so far, but now we have some uses cases where it's mandatory to receive an higher indeterminate number of elements.
The $http
-method returns a promise but I must rely on this data to make another request.
My simplified code:
var data =
"q=" + term
"×tamp=" + latest
$http({
method: 'POST',
url: url,
data: data
}).then(
function(response) {
let dataList = response.data.list;
if(dataList.length > 50)
/*TODO: new query with other timestamp-value*/
return dataList ;
},
function(response) {
if(shouldLog){
console.log("[DebuggingService] " + response);
}
}
);
Is there a way to combine multiple http requests depending on the request before?
EDIT
There is not pagination. So it's mandatory to change the timestamp value. (taking the latest timestamp of the response)
Upvotes: 0
Views: 101
Reputation: 171679
I would wrap that request in a function that can also be called recursively inside then()
to return another request promise
Something like:
function getData(term, time, res = []) {
var data = "q=" + term + "×tamp=" + time
// return the $http promise
return $http({
method: 'POST',
url: url,
data: data
}).then(function(response) {
let dataList = response.data.list;
// merge new data into final results array
res = res.concat(dataList);
if (dataList.length > 50) {
const timeStampFromResponse = //????
// return new request promise
return getData(term, timeStampFromResponse, res)
}
// return final array
return res;
})
}
getData(term, latest).then(function(results) {
// all results available here
}).catch(function(response) {
if (shouldLog) {
console.log("[DebuggingService] " + response);
}
})
Upvotes: 1
Reputation: 3166
Why not do something like this:
var data =
"q=" + term + "×tamp=" + latest;
var amounts = 2;
url = 'https://api.github.com/search/repositories?q=topic:ruby+topic:rails';
call(url, data, checkForMore);
function call(url, data, callback) {
$http({
method: 'POST',
url: url,
data: data
}).then(function(data){
console.log(data);
console.log('------------');
callback(data);
});
}
function checkForMore(data){
if (amounts > 0){
amounts -= 1;
var newData = "q=" + term +
"×tamp=" + data.SomehowGetLastestTimestamp;
call(url, newData, checkForMore);
} else {
// Save it maybe?
}
}
This is a very rough example, and probably doesn't work but it gets you a good idea what to do.
Basically, have a callback method that is called on the .then
anonymous function. Then you can pass in the data and check to see if you need to call it more. (Based on your situations). If you do, then just call the call
function again, but update your data.
Upvotes: 1