3 ms·
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 whil
by ch49 10y 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.
- mstade 10y agoI'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.
- Klathmon 10y agothe 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.
- eloisant 10y agoThat'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.
- matt42 10y agoI 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.
- ilkkao 10y agoReason is mentioned here: https://github.com/tc39/ecmascript-asyncawait/issues/88#issuecomment-181517500 https://github.com/tc39/ecmascript-asyncawait/issues/88#issu...
- mstade 10y agoThanks for this! Also later in that thread is an example to further bring home the point: https://github.com/tc39/ecmascript-asyncawait/issues/88#issuecomment-181574985 https://github.com/tc39/ecmascript-asyncawait/issues/88#issu... Solid reasoning, in my opinion.
- Bognar 10y agoIn 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.