Promises in parallel using async/await and Promise.all
ES7 brings async/await which, for the most part, replaces promise chains for asynchronous function calls. But the ES6 promise object still has some fancy tricks up its sleeves that can't be abstracted out.
If promises dont rely on each other, run them in parallel
Use Promise.all like a synchronous "checkpoint".
await Promise.all
It accepts an array of promises and only returns a value after all promises are
resolved. This means you can pass in promises that are currently running that
will always resolve before the subsequent lines of code are run.
Sample Promises
const sendText = text => {
return new Promise(function(resolve, reject) {
setTimeout( _ => resolve(text), 2000)
})
}
const chainText = (prevText, newText) => { //relies on value from sendText
return new Promise(function(resolve, reject) {
setTimeout( _ => resolve(prevText + newText), 2000)
})
}
Must be synchronous
const chainedPromises = async () => {
const text = await sendText('Sally')
const chainedText = await chainText(text, ' loves dogs')
console.log(chainedText)
//4 seconds to finish
}
Needlessly synchronous
const allSyncedPromises = async () => {
const text = await sendText('Sally')
const otherText = await sendText(' loves dogs') //doesn't rely on the above function
console.log(text + otherText)
//4 seconds to finish
}
Parallel, synchronous only when needed
const parallelPromises = async () => {
const text = sendText('Sally')
const otherText = sendText(' loves dogs')
const [first, second] = await Promise.all([text, otherText])
//Promise.all + await, to ensure all promises are resolved before continuing
console.log(first + second)
//2 seconds to finish
}
Comments
Post a Comment