解释 function* (Generator faction)

function* 的解释

描述

原文

function* 是用来定义Generator function(生成器)的,返回一个Generator 对象。

Generator 是一个能够被保存和可以重复进入的方法,它的上下文内容(参数的绑定)都可以被保存,并在下一次进入的时得到恢复。

Generator 在JS中非常强大而又轻量级工具,尤其是在和Promises组合使用的时候,Generator 优雅地把异步变得像「同步」一样。我们都知道在古老的 js 开发中,都是使用层层回调来处理异步逻辑的例如CallbackInversion of Control
这种模式的表示其中包含异步方法的调用。

调用一个Generator function并不会立刻执行它的方法体,而是返回一个迭代器对象iterator。当这个迭代器对象iteratornext()方法被调用的时候,这个Generator function会返回一个特定的值,这个值可能是包含跟随在yield后的表达式的执行结果的一个对象,也可能是委托调用另一个yield* 后的Generation functionnext()方法返回的对象是包含了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}

学习随笔

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值