Last active
January 6, 2019 09:13
-
-
Save theatlasroom/8f50e00bdbb8abad3bf208484d2f4ab1 to your computer and use it in GitHub Desktop.
Parallel vs serial async await
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 items = 10 | |
async function delayedFunc(delay, i) { | |
return new Promise((resolve, reject) => { | |
console.log(`Start executing ${i}`) | |
setTimeout(() => { | |
console.log(`Finished ${i}`) | |
resolve() | |
}, delay) | |
}) | |
} | |
async function parallel(arr) { | |
console.log('***Start Parallel') | |
await Promise.all(arr.map(delayedFunc)) | |
console.log('***Finished Parallel\n') | |
return await arr; | |
} | |
async function series(arr) { | |
console.log('***Start Series') | |
let counter = 0 | |
for (item of arr) { | |
await delayedFunc(item, counter) | |
counter++ | |
} | |
console.log('***Finished Series\n') | |
return await arr; | |
} | |
async function* genDelayedFunction(arr) { | |
let counter = 0; | |
for (const item of arr) { | |
await delayedFunc(item, counter); | |
yield `Delayed ${counter} by ${item}ms\n` | |
counter++ | |
} | |
} | |
async function asyncIteration(arr) { | |
// for-await-of is currently at stage-4 (2018/Dec) | |
// for-await-of can be used within async functions and anywhere await calls can be used | |
console.log('***Start asyncIteration') | |
for await (const item of genDelayedFunction(arr)) { | |
console.log(item); | |
} | |
console.log('***Finished asyncIteration\n') | |
return await arr; | |
} | |
async function exec() { | |
const arr = Array(items).fill(0).map((item, i) => Math.floor(i < items / 2) ? i * 1000 : (items - i) * 1000) | |
await parallel(arr); | |
await series(arr); | |
await asyncIteration(arr); | |
return; | |
} | |
(async function () { | |
console.log('BEGIN\n') | |
await exec() | |
console.log('DONE') | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment