Last active
January 30, 2020 09:53
-
-
Save munkacsitomi/e0939d7789b0ed3d31d5fa9b671e5cfa to your computer and use it in GitHub Desktop.
async/await is great but avoid going too sequential
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
// Not recommended - too sequential | |
async function logInOrder(urls) { | |
for (const url of urls) { | |
const response = await fetch(url); | |
console.log(await response.text()); | |
} | |
} | |
// Recommended - nice and parallel | |
async function logInOrder(urls) { | |
// fetch all the URLs in parallel | |
const textPromises = urls.map(async url => { | |
const response = await fetch(url); | |
return response.text(); | |
}); | |
// log them in sequence | |
for (const textPromise of textPromises) { | |
console.log(await textPromise); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment