Async wrapper
TLDR
const sum = (a, b) => a + b
const subtract = (a, b) => a - b
const sumAsync = async (...args) => {
await delay(1000)
return sum(...args)
}
const subtractAsync = async (...args) => {
return await delay(500).then(() => subtract(...args))
}
function delay(timeout) {
return new Promise(resolve => {
setTimeout(resolve, timeout)
})
}
why
- you’ve got a synchronous function.
- you made an async function (e.g. delay())
- you want to wrap the synchronous function in an async wrapper
steps
your synchronous function
const sum = (a, b) => a + b
your async function. it returns a promise, that resolves at the completion of something (e.g. timeout in this instance)
function delay(timeout) {
return new Promise(resolve => {
setTimeout(resolve, timeout)
})
}
async await
using async await
- write your async function with an
asyncat the beginning of the function and anawaitwhere you need to perform your time consuming function
const sumAsync = async (...args) => {
await delay(1000)
return sum(...args)
}
then
using .then()
- or chain them together by first calling your time consuming function, and add a
.then()to the end to do the next thing
const subtractAsync = async (...args) => {
return delay(500).then(() => subtract(...args))
}
promises
i wouldn’t recommend Promise callbacks. but this is how it would go:
const subtractAsync = (...args) =>
new Promise(
resolve => {
// do something that requires async
resolve(subtract(...args))
},
error => console.error(error)
)
or if we’re still doing setTimeout():
const subtractAsync = (...args) =>
new Promise(
resolve => {
setTimeout(() => {
resolve(subtract(...args))
}, 500)
},
e => console.error(e)
)