async function* 异步函数*

The async function* declaration creates a binding of a new async generator function to a given name.
async function* 声明创建新的异步生成器函数到给定名称的绑定。

You can also define async generator functions using the async function* expression.
您还可以使用 async function* 表达式定义异步生成器函数。

Try it 尝试一下

Syntax 语法

js JS系列
async function* name(param0) {
  statements
}
async function* name(param0, param1) {
  statements
}
async function* name(param0, param1, /* …, */ paramN) {
  statements
}

Note: Async generator functions do not have arrow function counterparts.
注意:异步生成器函数没有箭头函数对应项。

Note: function and * are separate tokens, so they can be separated by whitespace or line terminators. However, there cannot be a line terminator between async and function, otherwise a semicolon is automatically inserted, causing async to become an identifier and the rest to become a function* declaration.
注意: function 并且是 * 单独的标记,因此它们可以用空格或行终止符分隔。但是,在 和 function 之间 async 不能有行终止符,否则会自动插入分号,从而 async 导致 成为标识符,其余部分成为 function* 声明。

Parameters 参数

name

The function name. 函数名称。

param Optional  param 自选

The name of a formal parameter for the function. For the parameters' syntax, see the Functions reference.
函数的形式参数的名称。有关参数的语法,请参阅函数参考。

statements Optional  statements 自选

The statements comprising the body of the function.
构成函数主体的语句。

Description 描述

An async function* declaration creates an AsyncGeneratorFunction object. Each time when an async generator function is called, it returns a new AsyncGenerator object, which conforms to the async iterator protocol. Every call to next() returns a Promise that resolves to the iterator result object.
async function* 声明创建一个 AsyncGeneratorFunction 对象。每次调用异步生成器函数时,它都会返回一个新 AsyncGenerator 对象,该对象符合异步迭代器协议。每次调用 to next() 都会返回解析为迭代器结果对象的 a Promise

An async generator function combines the features of async functions and generator functions. You can use both the await and yield keywords within the function body. This empowers you to handle asynchronous tasks ergonomically with await, while leveraging the lazy nature of generator functions.
异步生成器函数结合了异步函数和生成器函数的功能。您可以在函数体中同时使用 awaityield 关键字。这使您能够按照人体工程学处理异 await 步任务,同时利用生成器函数的惰性。

When a promise is yielded from an async generator, the iterator result promise's eventual state will match that of the yielded promise. For example:
当从异步生成器生成 promise 时,迭代器结果 promise 的最终状态将与生成的 promise 的状态匹配。例如:

js JS系列
async function* foo() {
  yield Promise.reject(1);
}

foo()
  .next()
  .catch((e) => console.error(e));

1 will be logged, because if the yielded promise rejects, the iterator result will reject as well. The value property of an async generator's resolved result will not be another promise.

async function* declarations behave similar to function declarations — they are hoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.

Examples

Declaring an async generator function

Async generator functions always produce promises of results — even when each yield step is synchronous.

js
async function* myGenerator(step) {
  await new Promise((resolve) => setTimeout(resolve, 10));
  yield 0;
  yield step;
  yield step * 2;
}

const gen = myGenerator(2);
gen
  .next()
  .then((res) => {
    console.log(res); // { value: 0, done: false }
    return gen.next();
  })
  .then((res) => {
    console.log(res); // { value: 2, done: false }
    return gen.next();
  })
  .then((res) => {
    console.log(res); // { value: 4, done: false }
    return gen.next();
  })
  .then((res) => {
    console.log(res); // { value: undefined, done: true }
    return gen.next();
  });

Using an async generator function to read a series of files

In this example, we read a series of files and only access its content when requested, using Node's fs/promises module.

js
async function* readFiles(directory) {
  const files = await fs.readdir(directory);
  for (const file of files) {
    const stats = await fs.stat(file);
    if (stats.isFile()) {
      yield {
        name: file,
        content: await fs.readFile(file, "utf8"),
      };
    }
  }
}

const files = readFiles(".");
console.log((await files.next()).value);
// Possible output: { name: 'file1.txt', content: '...' }
console.log((await files.next()).value);
// Possible output: { name: 'file2.txt', content: '...' }

Specifications

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

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
Deno
Node.js
async function* statement

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

See also