Created
April 20, 2020 19:50
-
-
Save Way/32fb3a3f39ec5198485dcf0714457a52 to your computer and use it in GitHub Desktop.
Fetch and wait for multiple requests using async, await, and Promise.all
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
async function fetchUrls(urls) { | |
try { | |
// Using Promise.all() coalesce multiple promises into a single "super-promise" | |
return await Promise.all( | |
// map urls to fetch requests and parse their response as json | |
urls.map(url => fetch(url).then(response => response.json())) | |
); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
// await is only valid in async function | |
(async function main() { | |
const response = await fetchUrls([ | |
// Example urls - replace them... | |
'https://jsonplaceholder.typicode.com/posts', | |
'https://jsonplaceholder.typicode.com/albums', | |
'https://jsonplaceholder.typicode.com/users' | |
]); | |
// Do whatever you want with the response. It holds a list of all resolved json responses | |
console.log({ response }) | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment