Skip to content

Instantly share code, notes, and snippets.

@robertgonzales
Created January 11, 2018 23:02
Show Gist options
  • Save robertgonzales/fa42784f54bf1d16af4fe40a1b9bae6a to your computer and use it in GitHub Desktop.
Save robertgonzales/fa42784f54bf1d16af4fe40a1b9bae6a to your computer and use it in GitHub Desktop.
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