I have been trying to create a function which calls a paginated API, loops though each of the pages and adds a JSON value to an array. I would like the function to return the array.
The function makes an initial call to the api and calculates the number of times it has to loop by counting the number of results returned from all the pages and divides by 10 (the number of results per page is 10). So far the function looks like this:
function loopPages(url) {
$.getJSON(url, function (data) {
var pages = Math.ceil(data.count/10 + 1);
var i;
var myList = [];
for (i = 1; i < pages; i++) {
$.getJSON("http://urladdress.com/?page=" + i, function (data) {
obj = data.results;
$.each(obj, function (k, v) {
myList.push(v.city_name);
});
return myList
});
}
});
}
loopPages('http://urladdress.com/?page=1');
I cannot, however, work out where the return statement should go and how to access the array from outside the function.
I have also looked for other solutions to this problem (which I guess is rather common) but found nothing. Any help much appreciated!