Why Do Javascript Functions Need To Have The Keyword "async"? Isn't The "await" Keyword Enough?
Solution 1:
From a language perspective, the async
/await
keywords in JavaScript are designed very closely to the way they work in C#.
I have an old blog post that describes some discussions around why async
was explicitly added in C#: see Inferring "async"
here. In short, adding keywords is a potentially breaking change to a language; imagine an existing app that uses a var await = false;
or something of that nature.
Or, for an example of how this could be more ambiguous, var await = function() {};
, which would be used as await (x);
. Looking at the usage await (x);
, the compiler would have a hard time deciding what kind of expression that is. You could argue that await
is a keyword unless there's a variable in scope with that name, but that gets really hairy.
A much cleaner solution is to introduce a pair of keywords, so async
(which is used only for functions and lambdas, and is not ambiguous) enables the await
keyword, but only within that scope. There are similar benefits to having function*
denote generators, rather than just the presence of yield
.
It's not only less ambiguous (maintaining backwards compatibility with code that uses await
for other things), but it is also easier for both software and humans to parse.
Post a Comment for "Why Do Javascript Functions Need To Have The Keyword "async"? Isn't The "await" Keyword Enough?"