Skip to content

Instantly share code, notes, and snippets.

@dallashuggins
Created July 5, 2019 03:50
Show Gist options
  • Save dallashuggins/23b9f762825af38aa0699ec4856d4642 to your computer and use it in GitHub Desktop.
Save dallashuggins/23b9f762825af38aa0699ec4856d4642 to your computer and use it in GitHub Desktop.
Asynchronous recursive function that loops through all pages of results. There's a delay because of the large number of entities in the response, so you'll see my comment about what to add if you don't want to wait.
const axios = require('axios');
const util = require('util');
const getEntity = async (page) => {
try {
let options = {};
options.method = "GET";
options.url = 'https://pokeapi.co/api/v2/pokemon';
options.headers = {};
options.headers['Content-Type'] = 'application/json';
options.headers['Accept'] = 'application/json';
options.params = {};
options.params.limit = 60;
options.params.offset = 60 * page;
options.json = true;
let response = await axios(options);
if (response.status === 200) {
let body = response.data.results;
return body;
} else {
throw new Error (response.body);
}
}
catch (e) {
console.log("Error getEntity:", util.inspect(e, {showHidden: false, depth: null}));
throw new Error (e);
}
}
let recursive = async (entity = [], i = 1) => {
try {
let response = await getEntity(i);
if (response.length === 0) { // add || i > 2 to get 3 pages if you don't want to wait a while
return entity || [];
} else {
entity = await entity.concat(response);
i++;
return await recursive(entity, i);
}
} catch (e) {
console.log("Recursive error:", util.inspect(e, {showHidden: false, depth: null}));
throw new Error (e);
}
};
async function main () {
try {
let response = await recursive();
console.log("response:", response)
return response;
} catch (e) {
console.log("Main function error:", util.inspect(e, {showHidden: false, depth: null}));
throw new Error(e);
}
}
main()
module.exports = main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment