Docs
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Generator/next
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/function*
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/yield
相关资料
- https://marswiz.com/blog/2021/03/10/%E7%8E%B0%E4%BB%A3JS%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-Generator-%E7%94%9F%E6%88%90%E5%99%A8/#14-generator-%E7%94%9F%E6%88%90%E5%99%A8
Case 1
```typescript function* gen() { while(true) { var value = yield null; console.log(value); } }
var g = gen(); console.log(g.next()); console.log(g.next(1)); console.log(g.next()); console.log(g.next(2));
- gen 内是死循环,next() 永不 done
- 执行过程
- g.next():输出 { value: null, done: false }
- g.next(1): 流程返回 gen 内,1 为整个 yield 语句的返回值,即 var value = 1,输出 1
- g.next(): 输出 { value: null, done: false }
- g.next(2): 流程再次返回到 gen 内,2 位整个 yield 语句的返回值,即 var value = 2,输出 2
- 结束
<a name="Pv2ux"></a>
# Case 2
```typescript
function* gen() {
while(true) {
var value = yield null;
console.log(value);
}
}
var g = gen();
console.log(g.next(1));
console.log(g.next(2));
- 与 case 1 是有区别的,这个例子是输出不了 1 的
- 执行过程
- g.next(1): 输出 { value: null, done: false }
- g.next(2): 流程返回 gen 内,2 为整个 yield 语句的返回值,即 var value = 2,输出 2
- 结束
- 这里第一步 g.next(1) 的传值 1 是没有意义的,是在接收 yield 返回给 next() 的过程