为什么javascript函数需要使用关键字“异步"?不是“等待"吗?关键字够吗? [英] Why do javascript functions need to have the keyword "async"? Isn't the "await" keyword enough?

查看:74
本文介绍了为什么javascript函数需要使用关键字“异步"?不是“等待"吗?关键字够吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,为什么下面的函数需要具有异步" ..没有使用足够具体的等待方式来使编译器毫无歧义地解析代码?

 #为什么我们在这里需要异步异步函数foo(){var user =等待getUser(user_id);console.log(用户);} 

是出于向后兼容的原因吗?(我想不出任何在标准Javascript中使用等待键盘的代码.)?

主要是为了清楚起见,使该函数使用新的async关键字吗?谢谢

解决方案

从语言的角度来看,JavaScript中的 async / await 关键字被设计为非常与它们在C#中的工作方式非常接近.

我有一篇旧博客文章,描述了有关为什么在C#中显式添加 async 的一些讨论:请参见此处推断异步" .简而言之,添加关键字是对语言的潜在突破.想象一个使用 var await = false; 或类似性质的现有应用.

或者,例如,有关如何使其更加模棱两可的示例,请使用 var await = function(){}; ,将其用作 await(x); .查看用法 await(x); ,编译器将很难确定哪种类型的表达式.您可能会争辩说 await 是一个关键字,除非在作用域中具有该名称的变量,但这确实很麻烦.

一种更简洁的解决方案是引入一个 pair 关键字,因此 async (仅用于函数和lambda,并且没有歧义)可以启用 await 关键字,但仅在该范围内.使用 function * 表示生成器有类似的好处,而不仅仅是 yield 的存在.

它不仅不那么模棱两可(保持与使用 await 进行其他事情的代码的向后兼容性),而且对于软件人来说都更容易解析./p>

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

解决方案

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.

这篇关于为什么javascript函数需要使用关键字“异步"?不是“等待"吗?关键字够吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆