Created
December 19, 2016 12:03
-
-
Save mtt87/f21b8ad3cfaa46a359fe1ef3e38ee3b4 to your computer and use it in GitHub Desktop.
Promise recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you don't call resolve the promise won't return anything.
Every time you're calling
fetchPagesyou'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