Last active
April 25, 2017 14:57
-
-
Save zanonnicola/b8b20822f48990946698ac1859ff4486 to your computer and use it in GitHub Desktop.
Pagination Issue
This file contains 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
const promiseWhile = (url, condition) => { | |
let nextUrl; | |
let counter = 0; | |
if (!nextUrl) { | |
nextUrl = url; | |
} | |
const list = []; | |
const fetchData = (list) => { | |
console.log(`Counter: ${counter++}`); | |
console.log(`Next Url: ${nextUrl}`); | |
return fetch(nextUrl) | |
.then(response => { | |
return response.json(); | |
}) | |
.then((data) => { | |
let nextPage = data.next_page; | |
console.log(`Next page from API: ${data.next_page}`); | |
if (data[condition] && !data.data.length == 0) { | |
list.push(data.data); | |
nextUrl = BASE_URL + this.normalizeURL(nextPage); | |
return fetchData(list); | |
} else { | |
return list; | |
} | |
}) | |
.catch(function(err) { | |
throw new Error("Bad response from server"); | |
}); | |
} | |
return fetchData(list); | |
} | |
// Calling the function.... | |
promiseWhile(url, 'has_next_page').then((data) => { | |
console.log(data); | |
// see the results in the below gist | |
}).catch((err) => { | |
console.log(err); | |
}); |
This file contains 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
This is the output from the console.log | |
I'm bulding URLs this way (http://localhost:3000/tint-api/p/20/11/14931312640/20/10) in order to use them from my client JS app. | |
👇 | |
Counter: 0 | |
Next Url: http://localhost:3000/tint-api/p/20/11/14931312640/20/10 | |
Next page from API: https://api.tintup.com/v1/feed/mayorney?api_token=MY_TOKEN&count=20&offset=24&ref_timestamp=14931312640&relative_offset=40&unique_offset=21 | |
Counter: 1 | |
Next Url: http://localhost:3000/tint-api/p/20/24/14931312640/40/21 | |
Next page from API: https://api.tintup.com/v1/feed/mayorney?api_token=MY_TOKEN&count=20&offset=45&ref_timestamp=14931312640&relative_offset=57&unique_offset=30 | |
Counter: 2 | |
Next Url: http://localhost:3000/tint-api/p/20/45/14931312640/57/30 | |
Next page from API: https://api.tintup.com/v1/feed/mayorney?api_token=MY_TOKEN&count=20&offset=1&ref_timestamp=14931312640&relative_offset=1&unique_offset=0 | |
[Array(20), Array(20), Array(17)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment