Created
April 12, 2017 02:12
-
-
Save hansnow/547573c4c643fcb753ff059082607844 to your computer and use it in GitHub Desktop.
run asynchronous task parallel or series
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
const wait = delay => { | |
return () => new Promise(resolve => { | |
setTimeout(() => { | |
console.log(`wait ${delay}ms`) | |
resolve() | |
}, delay) | |
}) | |
} | |
const wait200 = wait(200) | |
const wait500 = wait(500) | |
const wait1000 = wait(1000) | |
const parallel = async () => { | |
const start = new Date() | |
await Promise.all([wait200(), wait500(), wait1000()]) | |
console.log(`total ${new Date() - start}ms`) | |
} | |
const series = async () => { | |
const start = new Date() | |
await wait200() | |
await wait500() | |
await wait1000() | |
console.log(`total ${new Date() - start}ms`) | |
} | |
if (process.argv[2] === 'parallel') return parallel() | |
series() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment