Created
January 14, 2020 13:41
-
-
Save 1isten/0fa6006112a0a51380af4b9f724498aa to your computer and use it in GitHub Desktop.
recursively fetch Laravel paginated api
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 rFetch(url) { | |
return new Promise((resolve, reject) => { | |
const list = []; | |
const getData = async url => { | |
try { | |
await new Promise((resolve, reject) => { | |
setTimeout(() => resolve(), 1000); // force delay~ | |
}); | |
const { data } = await axios.get(url); | |
console.log(data.current_page); | |
list.push(...data.data); | |
let nextPageUrl = data.next_page_url; | |
if (nextPageUrl) { | |
nextPageUrl = nextPageUrl.replace(process.env.API_PROXY_URL, ''); | |
getData(nextPageUrl); | |
} else { | |
resolve(list); | |
} | |
} catch (error) { | |
reject(error); | |
} | |
}; | |
getData(url); | |
}); | |
} |
Author
1isten
commented
Jan 14, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment