Last active
January 10, 2020 03:32
-
-
Save justinwhall/933b74f14179f152fa30fc0eb11a3d28 to your computer and use it in GitHub Desktop.
Make multiple fetch request with Promise.all & async await.
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
const userUrls = [ | |
'https://api.github.com/users/justinwhall', | |
'https://api.github.com/users/codeprokid', | |
'https://api.github.com/users/jasonbahl', | |
]; | |
/** | |
* OPTION (A) Make multiple fetch request with Prmoise.all & async await. | |
*/ | |
const getUsers = async () => { | |
return await Promise.all( | |
userUrls.map(async user => { | |
const userRes = await fetch(user); | |
return await userRes.json(); | |
}) | |
); | |
}; | |
getUsers().then(data => console.log(data)); | |
/** | |
* OPTION (B) Using just promise all | |
*/ | |
const getUsers = () => { | |
const requests = userUrls.map(req => fetch(req)); | |
return Promise.all(requests).then(res => Promise.all(res.map(r => r.json()))); | |
}; | |
getUsers().then(data => console.log(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment