0

I know that if a function is async then it would return a promise. However if that's the case what would happen if all the functions used inside an application is prefixed with an async, even when it is not actually asynchronous?

Which means there could be 3 cases that the main function calling it would contain:

  1. at least one actual asynchronous function.
  2. all the functions that it is calling us actually asynchronous.
  3. none of the functions that it is calling is actually asynchronous

but yet in all the above conditions the functions that are being called are all prefixed async.

In such scenarios what would happen?

Temp O'rary
  • 5,366
  • 13
  • 49
  • 109
  • 1
    They’d all return promises which all need to be awaited, causing a lot of overhead and rescheduling for every single function call. – deceze Jan 06 '21 at 06:31
  • https://stackoverflow.com/questions/46900782/what-is-the-overhead-of-javascript-async-functions#46908880 – user202729 Jan 06 '21 at 06:34
  • It doesn't make sense to do so. They'd all return promises, but their evaluation *would still be synchronous*, as even `async` function run synchronously until the first `await`. However, the code `await`ing them would become really asynchronous, as even synchronously settled promises call their callbacks only *on the next tick*! So, as @deceze wrote, it would just make your (and others') code less performant and more complex. – FZs Jan 06 '21 at 06:36

2 Answers2

2

All async functions return a promise. So, if you use async on a synchronous function, then the only way to get a return value out of the function is with await or .then(). For a purely synchronous function, this makes the interface less simple to use than it could be. So, using async, when there is no point in doing so make the function more difficult to program with.

It can be done and then the caller just has to use await or .then() to get any return value. I personally wouldn't use async unless the operation really was asynchronous.

It's also a little less efficient to wrap a synchronous return value in a promise object, causing the unnecessary creation and then garbage collection of the promise on every synchronous function call that uses async. For a function that is called occasionally, this is unlikely to be noticed. For a function that might be called lots or in a tight loop or when called many times a performance-sensitive portion of the code, this may be very noticeable.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

An async function returns a promise even when you return nothing from that function. And even when there is no code inside:

async function play(){

}

Even this will return a promise. So, this epitomizes all your cases.

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35