Skip to content

Instantly share code, notes, and snippets.

@SamWSoftware
Created May 9, 2022 07:50
Show Gist options
  • Save SamWSoftware/b9dc34ecd56300b41b8c25ca408b6079 to your computer and use it in GitHub Desktop.
Save SamWSoftware/b9dc34ecd56300b41b8c25ca408b6079 to your computer and use it in GitHub Desktop.
forOf vs map with promise array
const testForOfAsync = async () => {
const start = Date.now();
const getFruits = [
new Promise((resolve) => {setTimeout(() => resolve('apple'), 10000)}),
new Promise((resolve) => {setTimeout(() => resolve('banana'), 100)}),
new Promise((resolve) => {setTimeout(() => resolve('orange'), 100)})
]
for await (const fruit of getFruits) {
console.log(fruit, Date.now() - start)
}
}
const testMapAsync = async () => {
const start = Date.now();
const getFruits = [
new Promise((resolve) => {setTimeout(() => resolve('apple'), 10000)}),
new Promise((resolve) => {setTimeout(() => resolve('banana'), 100)}),
new Promise((resolve) => {setTimeout(() => resolve('orange'), 100)})
]
await Promise.all(
getFruits.map(async (fruitPromise) => {
const fruit = await fruitPromise;
console.log(fruit, Date.now() - start)
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment