Last active
December 6, 2022 22:36
-
-
Save justrhysism/b9b079eed495de69d2cf98a7462bc17d to your computer and use it in GitHub Desktop.
Async Loops Sanity Check
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
const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); | |
const delays = [ | |
[200, 'should show second'], | |
[100, 'should show first'], | |
[300, 'should show third'] | |
] | |
async function processWithFor(array) { | |
for (const [ms, msg] of array) { | |
await delay(ms); | |
console.log('processWithFor:', msg); | |
} | |
} | |
async function processWithForEach(array) { | |
array.forEach(async ([ms, msg]) => { | |
await delay(ms); | |
console.log('processWithForEach:', msg); | |
}); | |
} | |
async function processWithForAwait(array) { | |
for await (const [ms, msg] of array) { | |
await delay(ms) | |
console.log('processWithForAwait:', msg); | |
} | |
} | |
async function processWithPromiseAll(array) { | |
await Promise.all(array.map(async ([ms, msg]) => { | |
await delay(ms); | |
console.log('processWithPromiseAll:', msg); | |
})); | |
} | |
// processWithFor(delays).then(() => console.log('processWithFor done')); | |
// processWithForEach(delays).then(() => console.log('processWithForEach done')); | |
processWithForAwait(delays).then(() => console.log('processWithForAwait done')); | |
// processWithPromiseAll(delays).then(() => console.log('processWithPromiseAll done')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment