Context
Multiple await
calls will execute one after the other rather than in parallel. For example:
const someResult = await someCall()
const anotherResult = await anotherCall()
Here anotherCall()
will be called only when someCall()
is completed. What if you want to execute them in parallel?
Here's the simplest approach:
const [someResult, anotherResult] = await Promise.all([
someCall(),
anotherCall(),
])
Note that Promise.all
fails fast, which means that as soon as one of the promises supplied to it rejects, then the entire thing rejects. On the other hand, it will allow all the promises in it to run without blocking each other, but will prevent the execution to continue until ALL are resolved successfully.
For extra credit - here is a way to run many tasks in parallel and process the results individually as the tasks complete. I think it's pretty elegant.
function wait(ms, data) {
console.log('Starting task:', data, ms)
return new Promise((resolve) => setTimeout(resolve, ms, data))
}
// run these in parallel, process results individually
var tasks = [
async () => {
var result = await wait(1000, 'burrito')
// do something with result
console.log(result)
},
async () => {
var result = await wait(500, 'taco')
// do something with result
console.log(result)
},
async () => {
var result = await wait(5000, 'tostada')
// do something with result
console.log(result)
},
]
await Promise.all(tasks.map((p) => p()))
console.log('done')
There results should look as follows:
Starting task: burrito 1000
Starting task: taco 500
Starting task: tostada 5000
taco
burrito
tostada
done
References
Understanding Node.js Async Flows: Parallel, Serial, Waterfall and Queues