I'm using Ajax with JQuery to fetch data from an API that only returns 100 records at a time. If my query gives a result with more than 100 records, the API will include an "offset" parameter in the response. I have to use this offset parameter in new API call to get the next 100 records. The API will include a new offset parameter if there's even more records to fetch. And so on until all records are fetched.
I know how to push the result to an array, check if the offset parameter is in the result and if so, do another API call and push that result to the same array. But how do I construct a function that does all these ajax calls and let's me know when all the records have been fetched?
Below is how my function looks right now.
function getContracts(offset) {
var data = {};
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url,
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
contracts.push(this);
});
if (result.hasOwnProperty("offset")) {
getContracts(result.offset);
}
}
});
}