JS async/await - why does await need async?
Copied from https://stackoverflow.com/a/41744179/1483977 by @phaux:
These answers all give valid arguments for why the async keyword is a good thing, but none of them actually mentions the real reason why it had to be added to the spec.
The reason is that this was a valid JS pre-ES7
function await(x) { return 'awaiting ' + x } function foo() { return(await(42)) }
According to your logic, would
foo()
returnPromise{42}
or"awaiting 42"
? (returning a Promise would break backward compatibility)So the answer is:
await
is a regular identifier and it's only treated as a keyword inside async functions, so they have to be marked in some way.Fun fact: the original spec proposed more lightweight
function^ foo() {}
for async syntax.
I'm not privy to the JavaScript language design discussions, but I assume it's for the same reasons that the C# language requires async
(also see my blog).
Namely:
- Backwards compatibility. If
await
was suddenly a new keyword everywhere, then any existing code usingawait
as a variable name would break. Sinceawait
is a contextual keyword (activated byasync
), only code that intends to useawait
as a keyword will haveawait
be a keyword. - Easier to parse.
async
makes asynchronous code easier to parse for transpilers, browsers, tools, and humans.