为什么“异步"不是保留字? [英] Why is `async` not a a reserved word?

查看:109
本文介绍了为什么“异步"不是保留字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,规范文档await作为唯一的保留关键字不能使用async/await功能.

As far as I can tell, both the spec and the documentation have await as the only reserved keyword out of the async/await feature.

我们可以为变量async命名的事实进一步证明了这一点:

This is further demonstrated by the fact that we can name a variable async:

例如:

var async = 5;
console.log(async) // this is fine

节点(6.10)(也在 Repl.it 上)

Node (6.10) (also on Repl.it)

Chrome浏览器(59)

Firefox(54)

是因为向后兼容吗?我猜想许多代码库都会对某些功能使用名称async.

Is it because of backwards compatibility? I'd guess many codebases would use the name async for certain features.

这提供了一些看起来很奇怪的代码示例:

This allows for some strange looking code examples:

async function async() {
  var async = 5;
  await async;
  return async;
}
async().then(console.log)

无限递归承诺链? (并不是很重要,因为任何函数名都可以允许这样做,但是这段代码看起来还令人困惑)

Infinite recursive promise chain? (Not really important since any function name would allow this, however this code looks additionally confusing)

async function async() {
  await async();
}
// stackoverflow (might need to open your console to see the output)

推荐答案

async不必是保留字,因为可以对其进行唯一标识.可能发生这种情况的背景是诸如

async does not need to be a reserved word, because it can be uniquely identified. The contexts in which it can occur are those such as

async function() { }
async () => { }
obj = { async foo() { } };

除了将async指示为异步功能以外,所有其他方式均无法解析.

All of these could not be parsed in any way other than seeing async as indicating an async function.

另一方面,await在理论上可以用在诸如

On the other hand, await can in theory be used in a statement such as

async function foo() {
  await(1);
}

这是模棱两可的;是await在等待值1,还是使用参数1调用的函数?因此,await必须是保留字(在异步函数内部;在外部,可以随时将其用作变量).

which is ambiguous; is await awaiting the value 1, or is it a function being called with the parameter 1? Therefore, await needs to be a reserved word (inside async functions; outside, feel free to use it as a variable).

请记住,自JavaScript诞生以来,它已经有了很大的发展.许多单词被指定为保留字,然后从不使用,或者在技术上可能不需要保留时将其指定为保留字.将await指定为保留字(在模块内),以及不指定async作为保留字,是其设计者对该语言有了更成熟理解的产物.

Remember that JavaScript has evolved greatly since its origin. Many words were designated as reserved, and then never used, or designated as reserved when technically they might not need to have been. The designation of await as a reserved word (within modules), and the non-designation of async as a reserved word, are the product of a more mature understanding of the language on the part of its designers.

这篇关于为什么“异步"不是保留字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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