4

I am wrapping a function returning a promises into an async function on a small helper function...

trash(filesArray, {
    glob: false
})
.then(() => {
    resolve(true);
}).catch((err) =>  {
    return err;
})

…because I like to use it synchronous using the await on the next-higher level:

async empty(liveMode, force) {
    …
    await helpers.trashSync(trashFiles);
    // then doing further stuff...
}

Of course, this means, that I need to use the async keyword again... (otherwise I am told await is an ‘unknown reserved’ word or such) and if I am not mistaken, I will now need to use await again on the next-higher level?

await memberSet.empty(true, false)

Does this “game” continue all the way up and throughout my application, so by the end, I have plenty of async/await's wherever there's a tiny async function contained?

Or am I simply missing the point where to stop?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Frank N
  • 9,625
  • 4
  • 80
  • 110
  • "*I like to use it synchronous*" - that's not possible. An asynchronous function always finishes in the future. "*using the await*" just makes your function asynchronous, i.e. returning a promise that resolves in the future after something has been awaited. – Bergi Apr 15 '18 at 13:31
  • You might want to take a look at [this](https://stackoverflow.com/a/45448272/1048572). – Bergi Apr 15 '18 at 13:32
  • Also [this question](https://stackoverflow.com/questions/35380162/is-it-ok-to-use-async-await-almost-everywhere) – Bergi Apr 15 '18 at 18:35

1 Answers1

1

You can't convert an async function into a sync function, the purpose of async/await is to allow you to write code that has a similar code path to synchronous calls, but allowing the event loop to be re-entrant and therefore more fine grained. Generator/yield is an alternative approach to interrupting flow of execution.

You'll need to find a point where your call stack naturally expects a returned promise, or doesn't care that it completes asynchronously.

Dave Meehan
  • 3,133
  • 1
  • 17
  • 24