Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Promise.all using only async await.
const delay = ms => new Promise(r => setTimeout(r, ms))
async function AwaitAll() {
try {
const promises = [
delay(1000),
delay(250),
delay(500),
]
for (let p of promises) await p
console.log("success")
} catch (e) {
console.log("failed")
} finally {
console.log("done")
}
}
const delay = ms => new Promise(r => setTimeout(r, ms))
// First we need to understand that await runs in sequence.
async function AwaitInSequence() {
console.time()
await delay(1000)
await delay(250)
await delay(500)
console.timeEnd() // ~1750ms, since promises ran in sequence.
}
// This can be avoided by creating the promises before awaiting them.
async function AwaitInParallel() {
console.time()
const a = delay(1000)
const b = delay(250)
const c = delay(500)
await a
await b
await c
console.timeEnd() // ~1000ms, since promises ran in parallel.
}
// Promise.all works by resolving an array of promises in parallel.
function PromiseAll() {
const promises = [
delay(1000).then(() => console.log(1000)),
delay(250).then(() => console.log(250)),
delay(500).then(() => console.log(500)),
]
return Promise
.all(promises)
.then(() => console.log("success"))
.catch(() => console.log("failed"))
.then(() => console.log("done"))
}
// Here's an incorrect way of recreating Promise.all.
// Each promise will run in sequence (1750ms total delay).
async function AwaitAll() {
try {
await delay(1000).then(() => console.log(1000)),
await delay(250).then(() => console.log(250)),
await delay(500).then(() => console.log(500)),
console.log("success")
} catch (e) {
console.log("failed")
} finally {
console.log("done")
}
}
// Here's the correct way of recreating Promise.all.
// Each promise runs in parallel (1000ms total delay).
async function AwaitAll() {
try {
const promises = [
delay(1000).then(() => console.log(1000)),
delay(250).then(() => console.log(250)),
delay(500).then(() => console.log(500)),
]
for (let p of promises) await p
console.log("success")
} catch (e) {
console.log("failed")
} finally {
console.log("done")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment