Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JavaScript functions need to have the keyword "async"? Isn't the "await" keyword enough? [closed]

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?

like image 301
phzb0x Avatar asked Feb 26 '16 16:02

phzb0x


1 Answers

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.

like image 90
Stephen Cleary Avatar answered Sep 22 '22 08:09

Stephen Cleary