Skip to content

Instantly share code, notes, and snippets.

@Woodsphreaker
Last active November 2, 2017 13:39
Show Gist options
  • Save Woodsphreaker/4e7d8ba70e1e4d82e8b7f4f064571f20 to your computer and use it in GitHub Desktop.
Save Woodsphreaker/4e7d8ba70e1e4d82e8b7f4f064571f20 to your computer and use it in GitHub Desktop.
Async Test
const delay = (msg, time) =>
new Promise((res, rej) => {
setTimeout(() => res({msg: `${msg} in ${time}ms`, time: time}), time)
})
const fn1 = (msg = "fn1", time = 1000) => delay(msg, time)
const fn2 = (msg = "fn2", time = 2000) => delay(msg, time)
const fn3 = (msg = "fn3", time = 3000) => delay(msg, time)
const plus = (a = 0, b = 0) => a + b
const times = {
1:0,
2:0,
3:0
}
const allMessages = (acc, el) => {
acc += `(${el.msg})`
return acc
}
// *************** PROMISE *******************
fn1("Promise 1")
.then(res => {
console.log('--')
console.log('--')
console.log('--')
times[1] += res.time
console.log(`Result single promise (${res.msg}) - Total time: ${times[1]}ms`)
return fn2("Promise 2")
})
.then(res => {
console.log('--')
console.log('--')
console.log('--')
times[1] += res.time
console.log(`Result single promise (${res.msg}) - Total time: ${times[1]}ms`)
return fn3("Promise 3")
})
.then(res => {
console.log('--')
console.log('--')
console.log('--')
times[1] += res.time
console.log(`Result single promise (${res.msg}) - Total time: ${times[1]}ms`)
console.log('--')
console.log('--')
console.log('--')
})
// *************** PROMISE ALL *******************
console.time("Run Promise ALL in")
Promise.all([fn1(), fn2(), fn3()])
.then(res => {
console.log('--')
console.log('--')
console.log('--')
console.log(`Promise All *** ${res.reduce(allMessages, '')} ***`)
console.timeEnd("Run Promise ALL in")
})
// *************** PROMISE RACE *******************
console.time("Run Promise RACE in")
Promise.race([fn1(), fn2(), fn3()])
.then(res => {
console.log('--')
console.log('--')
console.log('--')
console.log(`Promise RACE *** ${res.msg} ***`)
console.timeEnd("Run Promise RACE in")
})
// *************** ASYNC / AWAIT *******************
const asyncMethod = async () => {
const p1 = await fn1()
const p2 = await fn2()
const p3 = await fn3()
console.log({p1, p2, p3}) // prints the result of the promises in a synchronous process
return [p1, p2, p3] // return all promises with pending status
}
console.time("Run Promise Async / Await in")
asyncMethod().then(res => {
console.log('--')
console.log('--')
console.log('--')
console.log(`Result async ${res.reduce(allMessages, '')}`)
console.timeEnd("Run Promise Async / Await in")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment