Symbol.asyncIterator

Symbol.asyncIterator 静态数据属性代表 众所周知的符号 @@asyncIterator异步可迭代协议 查找此符号以查找返回对象的异步迭代器的方法。为了使对象能够异步迭代,它必须具有 @@asyncIterator 键。

¥The Symbol.asyncIterator static data property represents the well-known symbol @@asyncIterator. The async iterable protocol looks up this symbol for the method that returns the async iterator for an object. In order for an object to be async iterable, it must have an @@asyncIterator key.

Try it

¥Value

众所周知的符号 @@asyncIterator

¥The well-known symbol @@asyncIterator.

Property attributes of Symbol.asyncIterator
Writable no
Enumerable no
Configurable no

示例

¥Examples

用户定义的异步迭代

¥User-defined async iterables

你可以通过在对象上设置 [Symbol.asyncIterator] 属性来定义自己的异步迭代。

¥You can define your own async iterable by setting the [Symbol.asyncIterator] property on an object.

js
const myAsyncIterable = {
  async *[Symbol.asyncIterator]() {
    yield "hello";
    yield "async";
    yield "iteration!";
  },
};

(async () => {
  for await (const x of myAsyncIterable) {
    console.log(x);
  }
})();
// Logs:
// "hello"
// "async"
// "iteration!"

创建 API 时,请记住,异步迭代旨在表示可迭代的事物(例如数据流或列表),而不是在大多数情况下完全取代回调和事件。

¥When creating an API, remember that async iterables are designed to represent something iterable — like a stream of data or a list —, not to completely replace callbacks and events in most situations.

内置异步迭代

¥Built-in async iterables

核心 JavaScript 语言中没有异步可迭代的对象。某些 Web API(例如 ReadableStream)默认设置了 Symbol.asyncIterator 方法。

¥There is no object in the core JavaScript language that is async iterable. Some web APIs, such as ReadableStream, have the Symbol.asyncIterator method set by default.

规范

Specification
ECMAScript Language Specification
# sec-symbol.asynciterator

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看