I'm trying to write a function that retrieves all of a user's data from an API. Unfortunately, the API only returns 50 pieces of data per request. In order to retrieve the next 'page' of results, another GET request needs to be made, with an extra path indicating the page of results.
(In my case, the API is Imgur, and the pieces of data are a user's albums.)
I'm trying to do this with Promises. The function populateAlbumList successfully returns only the first page of results.
I've attempted to modify it to get more pages of results in the function populateAlbumList2, but it's not working correctly.
How do I get these conditionally nested promises working? (I'd prefer not to use a library like bluebird/q, because I want to understand the concept and pattern itself.)
/**
* Performs an AJAX get request to the Imgur API, retrieving all the albums owned by the user. When the albums are
* populated, they are logged to the extension settings page's console.
* @returns {Promise<void>}
*/
async function populateAlbumList() {
const username = await getItemFromStorage(STORAGE_USERNAME, ERROR_STORAGE_USERNAME_NOT_FOUND);
const ALBUMS_URL = `https://api.imgur.com/3/account/${username}/albums`;
// Fetch the albums for the currently logged in user
return fetch(ALBUMS_URL, {
method: "GET",
headers: {
"Authorization": "Bearer " + CLIENT_ID,
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => json.data)
.then(albums => albums.forEach(album => addAlbumToPage(album)));
}
/**
* Performs an AJAX get request to the Imgur API, retrieving all the albums owned by the user. When the albums are
* populated, they are logged to the extension settings page's console.
* @returns {Promise<Array>}
*/
async function populateAlbumList2() {
const username = await getItemFromStorage(STORAGE_USERNAME, ERROR_STORAGE_USERNAME_NOT_FOUND);
let ALBUMS_URL = `https://api.imgur.com/3/account/${username}/albums`;
const allAlbums = [];
let page = 0;
const promises = [];
await getAlbumsFromImgur()
.then(() => console.log(allAlbums));
function getAlbumsFromImgur() {
if (page > 0) {
ALBUMS_URL = `https://api.imgur.com/3/account/${username}/albums` + page;
}
promises.push(
fetch(ALBUMS_URL, {
method: "GET",
headers: {
"Authorization": "Bearer " + CLIENT_ID,
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => json.data)
.then(albums => {
allAlbums.push(albums);
if (albums.length >= 50) {
page++;
promises.push(getAlbumsFromImgur());
}
})
);
}
}