更新时间:2023-02-24 19:54:40
首先,我们需要对其余答案进行一些澄清,以使其更有意义:
First, we need to clarify some things for the rest of the answer to make more sense:
async
关键字.有一个async function
构造: MDN , ECMAScript语言规范.因此,async
仅在后接函数时才具有特殊含义-作为表达式(传统函数和箭头函数)或声明.因此,称为async
的变量是有效的,因为后跟function
的变量在语法上无效.与语义没有冲突:async
keyword. There is an async function
construct: MDN, ECMAScript language specifications. So async
only has a special meaning if followed by function - either as an expression (both traditional and an arrow function) or as a declaration. Thus, a variable called async
is valid, since a variable followed by function
is not syntactically valid. There is no *** with semantics:
let foo;
//function declaration
foo function bar() {}; //SyntaxError
let foo;
//function expression
let bar = foo function() {}; //SyntaxError
await
一样,await
表达式(MDN):链接至规范.语义要求await
后跟一元表达式,并且必须位于async
函数内部-某些语法在语法上仍然无效.await
, that's actually an operator, not a keyword and it is part of an await
expression (MDN): link to the specs. The semantics require await
to be followed by a unary expression and to be inside an async
function - something that's still not syntactically valid with other variables.我没有任何消息来源,但是有理由得出这样的结论是为了保持向后兼容性而得出的结论是合理的.如果在ES5中有代码将async
用作变量,则稍后会突然中断.通过使async
仅在否则会出现SyntaxError的地方有效,可以确保旧代码和新代码可以共存.与await
相同.
I don't have any source for this but it's reasonable to conclude that this has been done to preserve backwards compatibility. If there was code that used async
as a variable in ES5, it would suddenly break later. By making async
only valid where otherwise you get a SyntaxError, that ensures that old code and new code can coexist. Same for await
.
有趣的是,await
的语义实际上导致了最初又很奇怪的行为-您不能将其用作async
函数中的变量.要么声明它:
Interestingly, the semantics of await
actually lead to behaviour that is again initially strange - you cannot use it as a variable inside an async
function. Either declaring it:
async function foo() {
let await = "world"; //SyntaxError - not a valid identifier here
}
不访问它:
let await = "world"; //valid identifier
async function foo() {
console.log(await); //SyntaxError - it is not followed by an expression
}
这在开始时也是令人困惑的,但是,向后兼容是有意义的.即使ES6之前的代码将await
用作变量,也不会在async
函数中使用它,因为不存在这些功能.因此,旧代码有效,并且仍然没有冲突.
This is initially confusing as well, however, it makes sense for backwards compatibility. Even if pre ES6 code used await
as a variable, it wouldn't have used it in async
functions as those didn't exist. So, old code works and there are still not ***es.