AsyncIterator

AsyncIterator 对象是通过提供 next() 方法来符合 异步迭代器协议 的对象,该方法将承诺履行返回到迭代器结果对象。AsyncIterator.prototype 对象是一个隐藏的全局对象,所有内置异步迭代器都继承自该对象。它提供了一个返回异步迭代器对象本身的 [Symbol.asyncIterator]() 方法,使异步迭代器也成为 异步可迭代

¥An AsyncIterator object is an object that conforms to the async iterator protocol by providing a next() method that returns a promise fulfilling to an iterator result object. The AsyncIterator.prototype object is a hidden global object that all built-in async iterators inherit from. It provides an [Symbol.asyncIterator]() method that returns the async iterator object itself, making the async iterator also async iterable.

请注意,AsyncIterator 不是全局对象,尽管将来它会与 异步迭代器助手提案 一起出现。所有内置异步迭代器共享的 AsyncIterator.prototype 对象可以通过以下代码获得:

¥Note that AsyncIterator is not a global object, although it will be in the future with the async iterator helpers proposal. The AsyncIterator.prototype object shared by all built-in async iterators can be obtained with the following code:

js
const AsyncIteratorPrototype = Object.getPrototypeOf(
  Object.getPrototypeOf(Object.getPrototypeOf((async function* () {})())),
);

描述

¥Description

目前,唯一内置的 JavaScript 异步迭代器是 异步生成器函数 返回的 AsyncGenerator 对象。Web API 中还有一些其他内置异步迭代器,例如 ReadableStream

¥Currently, the only built-in JavaScript async iterator is the AsyncGenerator object returned by async generator functions. There are some other built-in async iterators in web API, such as the one of a ReadableStream.

每个异步迭代器都有一个不同的原型对象,它定义特定异步迭代器使用的 next() 方法。所有这些原型对象都继承自 AsyncIterator.prototypeAsyncIterator.prototype 提供了返回异步迭代器对象本身的 [Symbol.asyncIterator]() 方法,使得异步迭代器也是 异步可迭代

¥Each of these async iterators have a distinct prototype object, which defines the next() method used by the particular async iterator. All of these prototype objects inherit from AsyncIterator.prototype, which provides an [Symbol.asyncIterator]() method that returns the async iterator object itself, making the async iterator also async iterable.

注意:AsyncIterator.prototype 没有实现 [Symbol.iterator](),因此默认情况下异步迭代器不是 同步可迭代

¥Note: AsyncIterator.prototype does not implement [Symbol.iterator](), so async iterators are not sync iterable by default.

实例方法

¥Instance methods

AsyncIterator.prototype[Symbol.asyncIterator]()

返回异步迭代器对象本身。这允许异步迭代器对象也可以异步迭代。

示例

¥Examples

使用异步迭代器作为异步迭代器

¥Using an async iterator as an async iterable

所有内置异步迭代器也是异步可迭代的,因此你可以在 for await...of 循环中使用它们:

¥All built-in async iterators are also async iterable, so you can use them in a for await...of loop:

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看