Why do javascript functions need to have the keyword “async”? Isn't the “await” keyword enough? [closed]

夙愿已清 提交于 2021-02-20 10:19:19

问题


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 use the await keyboard in standard Javascript..)?

Is it mainly for clarity to make it clear that this function uses the new async keyword? Thanks


回答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.



来源:https://stackoverflow.com/questions/35656423/why-do-javascript-functions-need-to-have-the-keyword-async-isnt-the-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!