Generator function
Cú pháp
Generator là hàm có dấu *, có thể tạm dừng tại mỗi yield và tiếp tục sau đó.
function* countdown(from) {
while (from > 0) {
yield from--;
}
return "Hết giờ"; // value của lần next() có done: true
}
const gen = countdown(3); // chưa chạy dòng nào!
gen.next(); // { value: 3, done: false }
gen.next(); // { value: 2, done: false }
gen.next(); // { value: 1, done: false }
gen.next(); // { value: "Hết giờ", done: true }
[...countdown(3)]; // [3, 2, 1] — for...of và spread bỏ qua giá trị returnObject generator vừa là iterator vừa là iterable.
Viết lại Range bằng generator
class Range {
constructor(from, to, step = 1) {
Object.assign(this, { from, to, step });
}
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n += this.step) yield n;
}
}So với bài trước: từ ~15 dòng còn 3 dòng.
Chuỗi vô hạn
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
for (const n of fibonacci()) {
if (n > 50) break; // break → generator tự dừng
console.log(n); // 0 1 1 2 3 5 8 13 21 34
}yield* — ủy quyền cho iterable khác
function* walk(tree) {
yield tree.name;
for (const child of tree.children ?? []) yield* walk(child);
}
const tree = { name: "src", children: [{ name: "lib", children: [{ name: "utils.js" }] }, { name: "main.js" }] };
[...walk(tree)]; // ["src", "lib", "utils.js", "main.js"]Truyền giá trị vào generator
next(x) làm cho biểu thức yield trả về x:
function* conversation() {
const name = yield "Bạn tên gì?";
const age = yield `Chào ${name}! Bạn bao nhiêu tuổi?`;
return `${name}, ${age} tuổi`;
}
const c = conversation();
c.next().value; // "Bạn tên gì?"
c.next("An").value; // "Chào An! Bạn bao nhiêu tuổi?"
c.next(20).value; // "An, 20 tuổi"Ngoài ra còn gen.return(value) (kết thúc sớm) và gen.throw(err) (ném lỗi vào tại vị trí yield).
Async generator
Kết hợp async và * để sinh dữ liệu bất đồng bộ — ví dụ đọc API phân trang. Bạn sẽ gặp lại ở chương 9:
async function* fetchAllPages(url) {
while (url) {
const res = await fetch(url);
const { items, next } = await res.json();
yield* items;
url = next;
}
}
for await (const item of fetchAllPages("/api/products?page=1")) {
console.log(item);
}
Comments