Skip to content

Instantly share code, notes, and snippets.

@mtt87
Created December 19, 2016 12:03
Show Gist options
  • Select an option

  • Save mtt87/f21b8ad3cfaa46a359fe1ef3e38ee3b4 to your computer and use it in GitHub Desktop.

Select an option

Save mtt87/f21b8ad3cfaa46a359fe1ef3e38ee3b4 to your computer and use it in GitHub Desktop.
Promise recursion
function fetchPages(resultsArray, page, end) {
return new Promise((resolve, reject) => {
fetch(`https://my-api.com/?page=${page}`)
.then((res) => {
// res.json
// {
// data: [1,2,3],
// nextPage: 1,
// previousPage: 0,
// }
const { data, nextPage } = res;
console.log(nextPage);
const thisPageResults = resultsArray.concat(data);
if (nextPage !== null && nextPage < end) {
// doesn't work, it will call correctly the function (that returns a promise)
// and fetch the data but won't trigger the last resolve(thisPageResults)
return fetchPages(thisPageResults, nextPage, end);
// works - why?
return resolve(fetchPages(thisPageResults, nextPage, end));
}
return resolve(thisPageResults);
})
.catch(err => reject(err));
});
}
const resultsArray = [];
fetchPages(resultsArray, 0, 3)
.then(results => console.log(results))
.catch(err => console.log(err));
@framp
Copy link

framp commented Dec 19, 2016

If you don't call resolve the promise won't return anything.
Every time you're calling fetchPages you're creating a new Promise and you're calling resolve only on the last Promise you create.
By calling resolve(fetchPages...) you're calling resolve on all the promises from the last one to the first one.

That said, I'd rather not use new Promise: https://gist.github.com/framp/8e74dfa713049be1ca6b70e8a3557659

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment