Skip to content

Instantly share code, notes, and snippets.

@rvanmil
Created November 29, 2018 11:19
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 rvanmil/45811315b2680100d12e9d4b6b8c59db to your computer and use it in GitHub Desktop.
Save rvanmil/45811315b2680100d12e9d4b6b8c59db to your computer and use it in GitHub Desktop.
Parallel and sequential async processing
const randomTimeout = () => Math.floor(Math.random() * (3000 - 500)) + 500
const someAsyncProcess = message => new Promise(resolve => setTimeout(() => {
console.log(message)
resolve()
}, randomTimeout()))
const messages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const testParallel = async () => Promise.all(messages.map(async message => someAsyncProcess(message)))
const testSequential = async () => messages.reduce(async (previousPromise, message) => {
await previousPromise
return someAsyncProcess(message)
}, Promise.resolve())
const test = async () => {
console.log('Parallel run')
await testParallel()
console.log('--------------')
console.log('Sequantial run')
await testSequential()
}
test()
@lmahapatra-oliver-it
Copy link

lmahapatra-oliver-it commented Dec 3, 2018

Hoi René,

Even voor mijn duidelijkheid:

const testParallel = ASYNC () => Promise.all(messages.map(ASYNC message => someAsyncProcess(message)))
const testSequential = ASYNC () => messages.reduce(async (previousPromise, message) => {

Volgens mijn zijn de async-en niet nodig op regels 10 en 12 omdat jij binnen die functies geen await hebt gebruikt.

Klopt het?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment