Generator通过yield表达式向外传出数据,每次next()执行到yield时返回{value:...,done:false};yield*可委托另一可迭代对象逐项产出;return则返回{value:...,done:true}标志结束。

Generator 向外部传出数据,主要通过 yield 表达式 实现——它既是“暂停点”,也是“传出通道”。每次执行 next() 时,函数运行到下一个 yield,并将紧跟其后的值作为 { value: ..., done: false } 中的 value 返回给调用方。
yield 后跟表达式,决定传出内容
yield 不是语句,而是带返回值的表达式。它右边的值(可以是任意类型)就是 Generator 向外传递的数据:
-
yield 42→ 外部收到{ value: 42, done: false } -
yield "hello"→ 外部收到{ value: "hello", done: false } -
yield { a: 1, b: 2 }→ 外部收到该对象 -
yield someFunction()→ 先执行函数,再传出其返回值
多次 yield 实现逐次传出
一个 Generator 函数可包含多个 yield,每次调用 next() 都推进到下一个 yield,并传出对应值:
function* counter() {
yield 1;
yield 2;
yield 3;
}
const gen = counter();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
yield* 委托,间接传出另一个 Generator 的数据
用 yield* 可把控制权和产出权交给另一个可迭代对象(如另一 Generator、数组、字符串等),自动将其每一项依次 yield 出来:
立即学习“Java免费学习笔记(深入)”;
-
yield* [1, 2, 3]等价于yield 1; yield 2; yield 3; -
yield* anotherGen()会逐个产出anotherGen中所有yield的值
这是组织复杂数据流、复用 Generator 逻辑的常用方式。
注意:return 也会传出数据,但标记完成
当 Generator 执行到 return(或自然结束),会返回 { value: ..., done: true }。这个 value 也是向外传出的数据,但表示终结:
function* example() {
yield "start";
return "done";
}
const g = example();
console.log(g.next()); // { value: "start", done: false }
console.log(g.next()); // { value: "done", done: true }
后续再调用 next(),始终返回 { value: undefined, done: true }。


















