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)
})
}your synchronous function
const sum = (a, b) => a + byour 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)
})
}using async await
async at the beginning of the function and an await where you need to perform your time consuming functionconst sumAsync = async (...args) => {
await delay(1000)
return sum(...args)
}using .then()
.then() to the end to do the next thingconst subtractAsync = async (...args) => {
return delay(500).then(() => subtract(...args))
}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)
)