Hacker News new | ask | show | jobs
by ch49 3691 days ago
Why is "async" keyword needed? Can't JS engine infer from the use of "await" in a function that this function need to be async? I'm using async/await for a while now, and so many times I've introduced bugs in my code because i forget to put "async" in front of the function, or put "async" in front of wrong function. It's simply annoying to go back and put "async" when in middle of writing a function I realise I need to use await.
5 comments

Thanks for this! Also later in that thread is an example to further bring home the point: https://github.com/tc39/ecmascript-asyncawait/issues/88#issu...

Solid reasoning, in my opinion.

I guess this is because you do not always want to wait for a future just after the function call. In some cases, there is code you want to execute between the call to an async function and the use of its return value.

A simple example would be the concurrent fetch of two urls.

In addition to the answers already given, I think it's important to notate that a function is async in the signature rather than requiring the user to scan the entire method looking for an "await" keyword.
That's how it works in C#, and personally I much prefer to have a clear declaration than having to rely on the interpreter parse the function to infer it's async.
I'd agree with you, and I'm keen to learn the real answer. My guess would be that some initial optimizations can occur without having to also parse and analyze the body of a function, potentially having significant performance benefits to reducing the boot time of a program.
the simple version is that because `await` wasn't a keyword before, it can be a named function.

So `await (x)` is ambiguous. Making the outer function `async function () {...}` makes await a keyword inside that function, allowing them to move forward with that syntax in a non-breaking way as the parser now knows that there can't be a function named `await` inside any async functions.