Gibran Shah
Gibran Shah

Reputation: 1109

Why do functions have to be async in order to use await within them?

If I want to await a function, why does that have to be done in an async function only?

If I have this:

Function myFunc() {
    return await myOtherFunc();
}

I get an error saying: “await expression is only allowed within an asynchronous function.”

I can understand if myOtherFunc() had to be asynchronous (it doesn't make sense to await an asynchronous function), but why does it care if the calling function is asynchronous or not. You can have a fork in a process within a synchronous function due to a call to an asynchronous function, right? So then why can’t you await that asynchronous function within the synchronous function?

NOTE: my question is NOT a duplicate of Javascript Await/Async Feature - What if you do not have the await word in the function?.

^ that question is asking what happens if await is not used in an async function. I'm asking why the function has to be async in order to use await. My response to DougBug below explains why they are different.

Upvotes: 1

Views: 153

Answers (1)

DougBug
DougBug

Reputation: 46

The picture in the following article might help explain it to you a bit.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/index

The basic idea though is that the async keyword allows the function to yield its execution up to a calling function.

As such any function that implements await must be marked async so that it can traverse back up the calling path until the first caller is only waiting on it to complete what it needs to do.

Upvotes: 1

Related Questions