Skip to content

Instantly share code, notes, and snippets.

@hansnow
Created April 12, 2017 02:12
Show Gist options
  • Save hansnow/547573c4c643fcb753ff059082607844 to your computer and use it in GitHub Desktop.
Save hansnow/547573c4c643fcb753ff059082607844 to your computer and use it in GitHub Desktop.
run asynchronous task parallel or series
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