语法错误:await/yield 表达式不能用于参数

JavaScript 异常 "await 表达式不能用于参数" 或当 默认参数 表达式包含 awaityield 关键字时,会发生 "yield 表达式不能用于参数",并具有暂停默认参数评估的效果。

¥The JavaScript exception "await expression can't be used in parameter" or "yield expression can't be used in parameter" occurs when the default parameter expression contains the await or yield keyword and has the effect of pausing default parameter evaluation.

信息

¥Message

SyntaxError: Illegal await-expression in formal parameters of async function (V8-based)
SyntaxError: await expression can't be used in parameter (Firefox)
SyntaxError: Cannot use 'await' within a parameter default expression. (Safari)

SyntaxError: Yield expression not allowed in formal parameter (V8-based)
SyntaxError: yield expression can't be used in parameter (Firefox)
SyntaxError: Unexpected keyword 'yield'. Cannot use yield expression within parameters. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

默认表达式必须能够同步评估。如果它包含 awaityield 表达式,它将暂停默认表达式的评估,这是不允许的。

¥The default expression must be able to evaluate synchronously. If it contains an await or yield expression, it will pause the evaluation of the default expression, which is not allowed.

注意:仅当 awaityield 是此函数上下文中的有效运算符时,才会生成此错误。否则,awaityield 将被解析为标识符,并且不会导致错误,或者如果后面有表达式,则会导致像 "保留标识符" 或 "意外的标记" 这样的错误。

¥Note: This error is only generated when await or yield are valid operators in this function context. Otherwise, await or yield would be parsed as an identifier, and either not cause an error, or cause an error like "reserved identifier", or "unexpected token" if there's an expression following it.

示例

¥Examples

无效案例

¥Invalid cases

js
function *gen(a = yield 1) {}

async function f(a = await Promise.resolve(1)) {}

有效案例

¥Valid cases

你可以使用 空值合并赋值 提供默认值。如果你想要以不同的方式处理 nullundefined,则需要使用条件。

¥You can use the nullish coalescing assignment to provide a default value instead. If you want to treat null and undefined differently, you would need to use a condition.

js
function* gen(a) {
  a ??= yield 1;
}

async function f(a) {
  a ??= await Promise.resolve(1);
}

如果表达式包含在初始化器的函数表达式中并且不会暂停默认表达式的评估,你也可以使用 awaityield

¥You are also allowed to use await or yield if the expression is contained in a function expression of the initializer and would not pause the evaluation of the default expression.

js
async function f(a = (async () => await Promise.resolve(1))()) {}

也可以看看