AsyncGeneratorFunction

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.

Đối tượng AsyncGeneratorFunction cung cấp các phương thức cho hàm async generator. Trong JavaScript, mỗi hàm async generator thực ra là một đối tượng AsyncGeneratorFunction.

Lưu ý rằng AsyncGeneratorFunction không phải là đối tượng toàn cục. Nó có thể được lấy bằng đoạn code sau:

js
const AsyncGeneratorFunction = async function* () {}.constructor;

AsyncGeneratorFunction là lớp con của Function.

Try it

const AsyncGeneratorFunction = async function* () {}.constructor;

const foo = new AsyncGeneratorFunction(`
  yield await Promise.resolve('a');
  yield await Promise.resolve('b');
  yield await Promise.resolve('c');
`);

let str = "";

async function generate() {
  for await (const val of foo()) {
    str += val;
  }
  console.log(str);
}

generate();
// Expected output: "abc"

Constructor

AsyncGeneratorFunction()

Tạo đối tượng AsyncGeneratorFunction mới.

Thuộc tính instance

Cũng kế thừa các thuộc tính instance từ lớp cha Function.

Các thuộc tính này được định nghĩa trên AsyncGeneratorFunction.prototype và được chia sẻ bởi tất cả các instance AsyncGeneratorFunction.

AsyncGeneratorFunction.prototype.constructor

Hàm constructor đã tạo đối tượng instance. Đối với các instance AsyncGeneratorFunction, giá trị khởi tạo là constructor AsyncGeneratorFunction.

AsyncGeneratorFunction.prototype.prototype

Tất cả các hàm async generator dùng chung cùng một thuộc tính prototype, đó là AsyncGenerator.prototype. Mỗi hàm async generator được tạo bằng cú pháp async function* hoặc constructor AsyncGeneratorFunction() cũng có thuộc tính prototype riêng của mình, có prototype là AsyncGeneratorFunction.prototype.prototype. Khi hàm async generator được gọi, thuộc tính prototype của nó sẽ trở thành prototype của đối tượng async generator được trả về.

AsyncGeneratorFunction.prototype[Symbol.toStringTag]

Giá trị khởi tạo của thuộc tính [Symbol.toStringTag] là chuỗi "AsyncGeneratorFunction". Thuộc tính này được dùng trong Object.prototype.toString().

Các thuộc tính này là thuộc tính riêng của mỗi instance AsyncGeneratorFunction.

prototype

Được dùng khi hàm được sử dụng như constructor với toán tử new. Nó sẽ trở thành prototype của đối tượng mới.

Phương thức instance

Kế thừa các phương thức instance từ lớp cha Function.

Đặc tả kỹ thuật

Specification
ECMAScript® 2027 Language Specification
# sec-asyncgeneratorfunction-objects

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

Xem thêm