Skip to content

Instantly share code, notes, and snippets.

@Way
Created April 20, 2020 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Way/32fb3a3f39ec5198485dcf0714457a52 to your computer and use it in GitHub Desktop.
Save Way/32fb3a3f39ec5198485dcf0714457a52 to your computer and use it in GitHub Desktop.
Fetch and wait for multiple requests using async, await, and Promise.all
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