Why should javascript have the keyword “async”? Is the word "waiting" enough?

For example, why should the function below have "async" .. doesn't use expectations enough so that the compiler can parse the code without ambiguity?

# Why do we need async here async function foo() { var user = await getUser(user_id); console.log(user); } 

Is this for backward compatibility reasons? (I can’t come up with any code that uses the standby keyboard in standard Javascript ..)?

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

+5
source share
1 answer

From a language point of view, the async / await keywords in JavaScript are very closely related to how they work in C #.

I have an old blog post that describes some discussions about why async was explicitly added in C #: see Inferring "async" here . In short, adding keywords is a potentially vulnerable change in language; imagine an existing application that uses var await = false; or something like that.

Or, for example, as it may be more ambiguous, var await = function() {}; to be used as await (x); . Looking at using await (x); , it would be difficult for the compiler to decide which expression. You can argue that await is a keyword unless a variable with that name is specified, but it gets really hairy.

A cleaner solution is to introduce a pair of keywords, so async (which is used only for functions and lambdas and is not ambiguous) allows you to use the await keyword, but only inside this area. Similar advantages are that function* stands for generators, not just the availability of yield .

Not only is it less ambiguous (while maintaining backward compatibility with code that await uses for other things), it is also easier to analyze for both software and people.

+6
source

Source: https://habr.com/ru/post/1243956/


All Articles