Generator appreciated execution of the function generator

Generator function is a basic format, the functions that you want to use the yield modifiers must precede the function name Number *

years, y = 0 ;
function * testYield(x){
console. log( 'before yield')
and = yield x + 1 ;
console. log( 'after yield')
return y ;
}

This function is called binding following code, call testYield ( . 1 )  and assigned to a time variable g, and any statement function is not performed in vivo, but a generated iterator assigned to the variable g

let g = testYield( 1);
console. log( 'before next')
let y1 = g. next();
console. log( 'first next call:', y1)
console. log( 'y:', y)
console. log( 'second next call:', g. next( 'str param')) // 等于y = yield,y被赋值为y1.value,如果这里next不传参,则y=undefined,而非x + 1
console. log( 'y:', y)
console. log( 'after next')

 

整个调用过程控制台打印如下

before next

before yield

first next call: {value: 2, done: false}--第一次next方法,next方法的返回值是一个对象,value属性是yield后面语句的返回值,done属性为布尔值,代表整个迭代过程是否已经结束

y: 0--可以看到,第一次执行next方法后,y的值仍然维持初始值不变,所以其实yield的作用是一个代码分界符,第一次调用next方法时函数执行到第一个yield后面的语句为止

after yield

second next call: {value: "str param", done: true}--第二次调用next方法后得到的value为字符串"str param",其实这个"str param"就是整个函数的return值,所以迭代器调用next方法的总次数为yield关键字的数量+1,

除最后一次调用next方法返回对象的value为函数的return值外,前面每次调用next方法返回对象的value值均为对应顺序的yield关键字后面语句的返回值,

但是要注意一点,第二次调用next方法的时候是传入参数"str param"的,如果不传,则最终y将为undefined,所以其实y = yield 可以理解为一个赋值语句,它赋的值第二次调用next方法时传入的参数,而非x + 1

y: str param --最终打印y的值也已经被修改为str param

after next

 

 

 

Guess you like

Origin www.cnblogs.com/kungfupan/p/11122233.html