For instance, why does the function below need to have "async"? Isn't using await specific enough for the compiler to parse the code without ambiguity?
// Why do we need async here?
async function foo() {
var user = await getUser(user_id);
console.log(user);
}
Is it for backward compatibility reasons? (I can't think of any code that uses the await keyboard in standard JavaScript...)?
Is it mainly for clarity to make it clear that this function uses the new async keyword?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With