Skip to content

Instantly share code, notes, and snippets.

@justrhysism
Last active December 6, 2022 22:36
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 justrhysism/b9b079eed495de69d2cf98a7462bc17d to your computer and use it in GitHub Desktop.
Save justrhysism/b9b079eed495de69d2cf98a7462bc17d to your computer and use it in GitHub Desktop.
Async Loops Sanity Check
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