[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function* [Back]  [Original]

async function* - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

async function*

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2020 1.

async function* binding .

async function* .

In this article

async function* foo() {
  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"

js
async function* name(param0) {
  statements
}
async function* name(param0, param1) {
  statements
}
async function* name(param0, param1, /* , */ paramN) {
  statements
}

: .

: function * . async function . , async function* .

name

.

param Optional

. .

statements Optional

.

async function* AsyncGeneratorFunction . AsyncGenerator . next() Promise .

. await yield . await , .

yield, yield .

js
async function* foo() {
  yield Promise.reject(new Error("failed"));
}

foo()
  .next()
  .catch((e) => console.error(e));

yield , Error: failed . value .

async function* function , .

yield .

js
async function* myGenerator(step) {
  await new Promise((resolve) => setTimeout(resolve, 10));
  yield 0;
  yield step;
  yield step * 2;
}

const gen = myGenerator(2);
gen
  .next()
  .then((res) => {
    console.log(res); // { value: 0, done: false }
    return gen.next();
  })
  .then((res) => {
    console.log(res); // { value: 2, done: false }
    return gen.next();
  })
  .then((res) => {
    console.log(res); // { value: 4, done: false }
    return gen.next();
  })
  .then((res) => {
    console.log(res); // { value: undefined, done: true }
    return gen.next();
  });

Node fs/promises , .

js
async function* readFiles(directory) {
  const files = await fs.readdir(directory);
  for (const file of files) {
    const stats = await fs.stat(file);
    if (stats.isFile()) {
      yield {
        name: file,
        content: await fs.readFile(file, "utf8"),
      };
    }
  }
}

const files = readFiles(".");
console.log((await files.next()).value);
// Possible output: { name: 'file1.txt', content: '...' }
console.log((await files.next()).value);
// Possible output: { name: 'file2.txt', content: '...' }

Specification
ECMAScript 2027 LanguageSpecification
# sec-async-generator-function-definitions


Web Proxy Viewer  |  New URL  |  Original Page