异步函数表达式

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.

async function 关键字可用于在表达式内定义异步函数。

¥The async function keywords can be used to define an async function inside an expression.

你还可以使用 async function 声明箭头语法 定义异步函数。

¥You can also define async functions using the async function declaration or the arrow syntax.

语法

¥Syntax

js
async function (param0) {
  statements
}
async function (param0, param1) {
  statements
}
async function (param0, param1, /* …, */ paramN) {
  statements
}

async function name(param0) {
  statements
}
async function name(param0, param1) {
  statements
}
async function name(param0, param1, /* …, */ paramN) {
  statements
}

注意:表达式语句 不能以关键字 async function 开头,以避免与 async function 声明 产生歧义。async function 关键字仅在出现在无法接受语句的上下文中时才开始表达式。

¥Note: An expression statement cannot begin with the keywords async function to avoid ambiguity with an async function declaration. The async function keywords only begin an expression when they appear in a context that cannot accept statements.

参数

¥Parameters

name Optional

函数名称。可以省略,在这种情况下该函数是匿名的。该名称仅是函数体的局部名称。

paramN Optional

函数的形式参数的名称。有关参数的语法,请参阅 函数参考

statements Optional

构成函数体的语句。

描述

¥Description

async function 表达式与 async function 声明 非常相似,并且具有几乎相同的语法。async function 表达式和 async function 声明之间的主要区别在于函数名称,在 async function 表达式中可以省略函数名称以创建匿名函数。async function 表达式可以用作 IIFE(立即调用函数表达式),它在定义后立即运行,允许你模仿 顶层等待。另请参阅有关 functions 的章节以获取更多信息。

¥An async function expression is very similar to, and has almost the same syntax as, an async function declaration. The main difference between an async function expression and an async function declaration is the function name, which can be omitted in async function expressions to create anonymous functions. An async function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined, allowing you to mimic top-level await. See also the chapter about functions for more information.

示例

¥Examples

使用异步函数表达式

¥Using async function expression

js
function resolveAfter2Seconds(x) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

// async function expression assigned to a variable
const add = async function (x) {
  const a = await resolveAfter2Seconds(20);
  const b = await resolveAfter2Seconds(30);
  return x + a + b;
};

add(10).then((v) => {
  console.log(v); // prints 60 after 4 seconds.
});

// async function expression used as an IIFE
(async function (x) {
  const p1 = resolveAfter2Seconds(20);
  const p2 = resolveAfter2Seconds(30);
  return x + (await p1) + (await p2);
})(10).then((v) => {
  console.log(v); // prints 60 after 2 seconds.
});

规范

Specification
ECMAScript Language Specification
# sec-async-function-definitions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看