Generator(三)
Iterator高级功能
给迭代器传递参数
可以通过next()方法给迭代器传递参数。当通过next()传递参数时,参数变成了yield语句在生成器中的值。这个能力对很多高级功能非常重要,例如异步编程。例子
function *createIterator() {
let first = yield 1;
let second = yield first + 2; // 4 + 2
yield second + 3; // 5 + 3
}
let iterator = createIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next(4)); // "{ value: 6, done: false }"
console.log(iterator.next(5)); // "{ value: 8, done: false }"
console.log(iterator.next()); // "{ value: undefined, done: true }"
首次调用next()比较特殊,传递任何参数都会丢失。此处第一次调用next(),执行到yield
1,输出1,然后停止执行;第二次调用next(4),参数为4,继续生成器的执行,4作为yield 1的值被赋给first,然后执行到yield first + 2,输出6,停止执行。整个执行过程如下图所示:
其中浅灰区域为第一次调用next执行的代码,中灰区域为第二次调用next执行的代码,深灰区域为第三次调用next执行的代码
在迭代器中抛出错误
除了可以给迭代器传递数据之外,还可以传递错误条件。迭代器实现了一个throw方法,可以在重新开始时让迭代器抛出错误。这对异步编程是一个很重要的能力,也提高了生成器内部的灵活性(可以像普通函数一样返回值和抛出错误)。例子:
function *createIterator() {
let first = yield 1;
let second = yield first + 2; // yield 4 + 2, then throw
yield second + 3; // never is executed
}
let iterator = createIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next(4)); // "{ value: 6, done: false }"
console.log(iterator.throw(new Error("Boom"))); // error thrown from generator
生成器中抛出错误
了解了这一点就可以在生成器中使用try-catch捕获这类错误,例子:
function *createIterator() {
let first = yield 1;
let second;
try {
second = yield first + 2; // yield 4 + 2, then throw
} catch (ex) {
second = 6; // on error, assign a different value
}
yield second + 3;
}
let iterator = createIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next(4)); // "{ value: 6, done: false }"
console.log(iterator.throw(new Error("Boom"))); // "{ value: 9, done: false }"
console.log(iterator.next()); // "{ value: undefined, done: true }"
生成器返回语句
生成器也是函数,所以也可以使用return语句提前退出或者给next方法的最后一次调用指定一个返回值。大多数情况下,Iterator上最后一次next调用返回undefined,但你可以利用return指定一个值。
例子1:
function *createIterator() {
yield 1;
return;
yield 2;
yield 3;
}
let iterator = createIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next()); // "{ value: undefined, done: true }"
例子2:
function *createIterator() {
yield 1;
return 42;
}
let iterator = createIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next()); // "{ value: 42, done: true }"
console.log(iterator.next()); // "{ value: undefined, done: true }"
注意:Spread Operator和for of循环会忽略return的返回值。它们只要确认done为true,就不再读取value的值。但是在委托生成器时return返回的值是有用的。
委托生成器(Delegating Generators)
在一些情况下,合并两个生成器的内容到一起是有用的。生成器可以使用一种特殊形式的yield(后面带星号)委托到其他生成器。和生成器定义一样,这个星号只要在yield和生成器函数之间即可。例子:
function *createNumberIterator() {
yield 1;
yield 2;
}
function *createColorIterator() {
yield "red";
yield "green";
}
function *createCombinedIterator() {
yield *createNumberIterator();
yield *createColorIterator();
yield true;
}
var iterator = createCombinedIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next()); // "{ value: 2, done: false }"
console.log(iterator.next()); // "{ value: "red", done: false }"
console.log(iterator.next()); // "{ value: "green", done: false }"
console.log(iterator.next()); // "{ value: true, done: false }"
console.log(iterator.next()); // "{ value: undefined, done: true }"
生成器委托也可以让我们充分利用return的返回值。例子:
function *createNumberIterator() {
yield 1;
yield 2;
return 3;
}
function *createRepeatingIterator(count) {
for (let i=0; i < count; i++) {
yield "repeat";
}
}
function *createCombinedIterator() {
let result = yield *createNumberIterator();
yield *createRepeatingIterator(result);
}
var iterator = createCombinedIterator();
console.log(iterator.next()); // "{ value: 1, done: false }"
console.log(iterator.next()); // "{ value: 2, done: false }"
console.log(iterator.next()); // "{ value: "repeat", done: false }"
console.log(iterator.next()); // "{ value: "repeat", done: false }"
console.log(iterator.next()); // "{ value: "repeat", done: false }"
console.log(iterator.next()); // "{ value: undefined, done: true }"
异步任务运行
生成器最令人兴奋的地方适合异步编程有关的。它能够让代码在执行过程中暂停,这为异步编程打开了一扇新的大门,让我们不必纠缠于多层嵌套的回调当中。
传统的回调方式处理异步编程:
let fs = require("fs");
fs.readFile("config.json", function(err, contents) {
if (err) {
throw err;
}
doSomethingWith(contents);
console.log("Done");
});
简单的任务运行器
function run(taskDef) {
// create the iterator, make available elsewhere
let task = taskDef();
// start the task
let result = task.next();
// recursive function to keep calling next()
function step() {
// if there's more to do
if (!result.done) {
result = task.next();
step();
}
}
// start the process
step();
}
run(function*() {
console.log(1);
yield;
console.log(2);
yield;
console.log(3);
});
带数据的任务运行器
function run(taskDef) {
// create the iterator, make available elsewhere
let task = taskDef();
// start the task
let result = task.next();
// recursive function to keep calling next()
function step() {
// if there's more to do
if (!result.done) {
result = task.next(result.value);
step();
}
}
// start the process
step();
}
run(function*() {
let value = yield 1;
console.log(value); // 1
value = yield value + 3;
console.log(value); // 4
});
异步任务运行器
let fs = require("fs");
function run(taskDef) {
// create the iterator, make available elsewhere
let task = taskDef();
// start the task
let result = task.next();
// recursive function to keep calling next()
function step() {
// if there's more to do
if (!result.done) {
if (typeof result.value === "function") {
result.value(function(err, data) {
if (err) {
result = task.throw(err);
return;
}
result = task.next(data);
step();
});
} else {
result = task.next(result.value);
step();
}
}
}
// start the process
step();
}
function readFile(filename) {
return function(callback) {
fs.readFile(filename, callback);
};
}
run(function*() {
let contents = yield readFile("config.json");
doSomethingWith(contents);
console.log("Done");
});