AsyncIterator.prototype[Symbol.asyncIterator]()

AsyncIterator 实例的 [Symbol.asyncIterator]() 方法实现了 异步可迭代协议,并允许大多数需要异步迭代的语法(例如 for await...of 循环)使用内置异步迭代器。它返回 this 的值,这是异步迭代器对象本身。

¥The [Symbol.asyncIterator]() method of AsyncIterator instances implements the async iterable protocol and allows built-in async iterators to be consumed by most syntaxes expecting async iterables, such as for await...of loops. It returns the value of this, which is the async iterator object itself.

Try it

语法

¥Syntax

js
asyncIterator[Symbol.asyncIterator]()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

this 的值,它是异步迭代器对象本身。

¥The value of this, which is the async iterator object itself.

示例

¥Examples

使用 for wait...of 循环进行迭代

¥Iteration using for await...of loop

请注意,你很少需要直接调用此方法。[Symbol.asyncIterator]() 方法的存在使得所有内置的异步迭代器都变成了 异步可迭代,像 for await...of 循环这样的迭代语法会自动调用该方法来获取要循环的异步迭代器。

¥Note that you seldom need to call this method directly. The existence of the [Symbol.asyncIterator]() method makes all built-in async iterators async iterable, and iterating syntaxes like the for await...of loop automatically calls this method to obtain the async iterator to loop over.

js
const asyncIterator = (async function* () {
  yield 1;
  yield 2;
  yield 3;
})();
(async () => {
  for await (const value of asyncIterator) {
    console.log(value);
  }
})();
// Logs: 1, 2, 3

规范

Specification
ECMAScript Language Specification
# sec-asynciteratorprototype-asynciterator

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also