0

Hi I was wondering how I could await a void function. I tried the following (mock up):

async function asyncer() {
  setTimeout(() => {
    console.log("async msg")
  }, 0)
}

async function helloer() {
  await asyncer()
  console.log("hello")
}

helloer()

This however doesn't work, so I tried the following :

async function asyncer() {
  setTimeout(() => {
    console.log("async msg")
  }, 0)
  return true
}

async function helloer() {
  let ready = await asyncer()
  if (ready) {
    console.log("hello")
  }
}

helloer()

Still "hello" is still logged before "async msg". Does anyone know a solution to this problem. Thanks in advance.

Andy
  • 61,948
  • 13
  • 68
  • 95
Jip Helsen
  • 1,034
  • 4
  • 15
  • 30
  • 2
    use `Promise` see here for more detail https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Alen.Toma Nov 18 '21 at 22:32
  • 2
    setTimeout doesn't block. `await` is for promises, of which there are none here. Please check the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) – Phix Nov 18 '21 at 22:33

1 Answers1

0

async/await is a syntax sugar for promise.then, so create a Promise.resolve or smth to enter in async flow and then use async/await