20200315
Plan
- 你不知道的 js 中卷 -- 生成器 + promise
Notes
生成器 + promise
生成器委托
- 在一个生成器中调用另一个生成器
function* foo() {
console.log("*foo starting");
yield 3;
yield 4;
console.log("*foo finished");
}
function* bar() {
yield 1;
yield 2;
yield* foo();
yield 5;
}
var it = bar();
it.next();
// {value: 1, done: false}
it.next();
// {value: 2, done: false}
it.next();
// *foo starting
// {value: 3, done: false}
it.next();
// {value: 4, done: false}
it.next();
// *foo finished
// {value: 5, done: false}
it.next();
// {value: undefined, done: true}
- 生成器委托中的消息传递
function* foo() {
console.log("inside *foo():", yield "b");
console.log("inside *foo():", yield "c");
return "d";
}
function* bar() {
console.log("inside *bar():", yield "a");
console.log("inside *bar():", yield* foo());
console.log("inside *bar():", yield "e");
return "f";
}
var it = bar();
it.next();
// {value: "a", done: false}
it.next("A");
// inside *bar(): A
// {value: "b", done: false}
it.next("B");
// inside *foo(): B
// {value: "c", done: false}
it.next("C");
// inside *foo(): C
// inside *bar(): d
// {value: "e", done: false}
it.next("E");
// inside *bar(): E
// {value: "f", done: true}
- 可以直接调用迭代器
function* foo() {
console.log("inside *foo():", yield "b");
console.log("inside *foo():", yield "c");
return "d";
}
function* bar() {
console.log("inside *bar():", yield "a");
console.log("inside *bar():", yield* ["b", "c", "d"]);
console.log("inside *bar():", yield "e");
return "f";
}
More
生成器在 babel 编译之后变成了什么?
async/await babel 编译之后变成 生成器 + promise 的模式。有时间可以研究一下