Symbol.asyncIterator

Baseline Widely available

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

Thuộc tính dữ liệu tĩnh Symbol.asyncIterator đại diện cho well-known symbol Symbol.asyncIterator. Giao thức async iterable tra cứu symbol này cho phương thức trả về async iterator cho một đối tượng. Để một đối tượng có thể là async iterable, nó phải có khóa [Symbol.asyncIterator].

Try it

const delayedResponses = {
  delays: [500, 1300, 3500],

  wait(delay) {
    return new Promise((resolve) => {
      setTimeout(resolve, delay);
    });
  },

  async *[Symbol.asyncIterator]() {
    for (const delay of this.delays) {
      await this.wait(delay);
      yield `Delayed response for ${delay} milliseconds`;
    }
  },
};

(async () => {
  for await (const response of delayedResponses) {
    console.log(response);
  }
})();

// Expected output: "Delayed response for 500 milliseconds"
// Expected output: "Delayed response for 1300 milliseconds"
// Expected output: "Delayed response for 3500 milliseconds"

Giá trị

Well-known symbol Symbol.asyncIterator.

Property attributes of Symbol.asyncIterator
Writableno
Enumerableno
Configurableno

Ví dụ

Async iterable do người dùng định nghĩa

Bạn có thể định nghĩa async iterable của riêng mình bằng cách đặt thuộc tính [Symbol.asyncIterator]() trên một đối tượng.

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!"

Khi tạo API, hãy nhớ rằng async iterable được thiết kế để đại diện cho thứ gì đó có thể lặp lại — như một luồng dữ liệu hoặc danh sách —, không phải để thay thế hoàn toàn callback và event trong hầu hết các tình huống.

Async iterable tích hợp sẵn

Không có đối tượng nào trong ngôn ngữ JavaScript cốt lõi là async iterable. Một số Web API, chẳng hạn như ReadableStream, có phương thức Symbol.asyncIterator được thiết lập mặc định.

Đặc tả

Specification
ECMAScript® 2027 Language Specification
# sec-symbol.asynciterator

Tương thích trình duyệt

Xem thêm