function* 的解释
描述
function* 是用来定义Generator function(生成器)的,返回一个Generator 对象。
Generator 是一个能够被保存和可以重复进入的方法,它的上下文内容(参数的绑定)都可以被保存,并在下一次进入的时得到恢复。
Generator 在JS中非常强大而又轻量级工具,尤其是在和Promises组合使用的时候,Generator 优雅地把异步变得像「同步」一样。我们都知道在古老的 js 开发中,都是使用层层回调来处理异步逻辑的例如Callback和Inversion of Control。
这种模式的表示其中包含异步方法的调用。
调用一个Generator function
并不会立刻执行它的方法体,而是返回一个迭代器对象iterator
。当这个迭代器对象iterator
的next()
方法被调用的时候,这个Generator function
会返回一个特定的值,这个值可能是包含跟随在yield
后的表达式的执行结果的一个对象,也可能是委托调用另一个yield*
后的Generation function
。next()
方法返回的对象是包含了yield
后随的表达式生成的值的value
属性,和一个表示Generation function
是否已经生成最后了一个值的布尔类型的done
属性。在调用next() 函数的时候如果传入了一个参数那么在Generation function
执行后,会将暂停处的yiled
后随表达式的位置替换成传来的参数值。
在Generation中一个返回语句return被执行时,它会使Generator整体进入完成状态,并返回对象,对象的done
属性被设置为true
,返回对象的value
属性是return的返回值。
许多类似于的return语句,error在Generation中被抛出同样会导致Generation进入完成状态,除非你在Generation内部捕获抛出的异常。
当Generation进入完成状态后,后续对它的next()调用都不会在执行Generation里面的任何代码,它只会返回一个这样格式的对象:{value:undefined,done:true}
。
看下面例子
例子
简单的例子
function* generator(i) {
yield i;
yield i + 10;
}
var gen = generator(10);
console.log(gen.next().value);
// expected output: 10
console.log(gen.next().value);
// expected output: 20
简单的yield*例子
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
function* generator(i) {
yield i;
yield* anotherGenerator(i);
yield i + 10;
}
var gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20
传参到generator中列子
function* logGenerator() {
console.log(0);
console.log(1, yield);
console.log(2, yield);
console.log(3, yield);
}
var gen = logGenerator();
// the first call of next executes from the start of the function
// until the first yield statement
gen.next(); // 0
gen.next('pretzel'); // 1 pretzel
gen.next('california'); // 2 california
gen.next('mayonnaise'); // 3 mayonnaise
在generator中返回语句的例子
function* yieldAndReturn() {
yield "Y";
return "R";
yield "unreachable";
}
var gen = yieldAndReturn()
console.log(gen.next()); // { value: "Y", done: false }
console.log(gen.next()); // { value: "R", done: true }
console.log(gen.next()); // { value: undefined, done: true }
generator不可创建对象
function* f() {}
var obj = new f; // throws "TypeError: f is not a constructor
genrator 被定义在表达式中
const foo = function* () {
yield 10;
yield 20;
};
const bar = foo();
console.log(bar.next()); // {value: 10, done: false}
学习随笔