20200313
Plan
- 你不知道的 js 中卷 生成器
Notes
回调异步的缺陷
- 不符合大脑对任务步骤的规划方式
- 由于控制反转,回调并不可信
Generator
var x = 1;
function* foo() {
// 也可以是 function *foo
x++;
yield;
console.log("x: ", x);
}
function bar() {
x++;
}
const iterator = foo(); // 并没有运行到foo生成器内部,而是构造了一个迭代器
iternator.next(); // 这里运行了foo中的第一部分: x++
bar();
iterator.next(); // 继续执行第二部分:console.log
定义 可以一次或多次启动和停止,并不一定非得要完成的一种特殊函数
返回值
- 返回值是一个 iterator,迭代器
- 迭代器可以在 for of 中循环
- 实现一个迭代器 -- 给一个对象定义一个 Symbol.iterator 属性,返回一个包含 next 方法的对象 demo
入参
- 生成器作为一个函数,可以有入参和返回值,直接调用并不会执行函数本身,而是构造了一个生成器
function* foo(x, y) {
return x + y;
}
let it = foo(6, 7); // it 在这里是一个生成器 __proto__ 指向 Generator
let res = it.next(); // 返回一个对象,执行了 x + y 这条语句。res.value === 13
消息传递
- 可以通过 yield 传值值
function* foo(x) {
let y = x * (yield);
return y;
}
let it = foo(6);
it.next(); // 运行到 let y = x * 处,等待下一个 next
it.next(7); // 第一个yield取7 value === 42
- yield 也可以返回一个值,消息可以双向传递
function* foo(x) {
var y = x * (yield yield);
return y;
}
let it = foo(6);
it.next(7);
it.next(8);