| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function* | [Back] [Original] |
Get to know MDN better
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 = str + val;
}
console.log(str);
}
generate();
// : "abc"
async function* name(param0) {
statements
}
async function* name(param0, param1) {
statements
}
async function* name(param0, param1, /* ,*/ paramN) {
statements
}
:
function* AsyncGenerator next() Promise
async function* foo() {
yield Promise.reject(1);
}
foo()
.next()
.catch((e) => console.error(e));
1 value
yield
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
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: '...' }
| ECMAScript 2027 LanguageSpecification # sec-async-generator-function-definitions |
| Web Proxy Viewer | New URL | Original Page |