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

  1. you've got a synchronous function.
  2. you made an async function (e.g. delay())
  3. 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

const sumAsync = async (...args) => {
  await delay(1000)
  return sum(...args)
}

then

using .then()

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)
  )