Simple to understand geneator

Formally, Generator function is a normal function, but there are two features. First, there is an asterisk between the function key and the function name; Second, the functions that use the yield statement, define different internal states

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}
var hw = helloWorldGenerator();

Generator function calls the method with normal function, but also after the function name with a pair of parentheses. The difference is that, after calling Generator function, which is not performed, nor is the function is to return the result, but a pointer to the internal state of the object, we can call the next method, so that the pointer moves to the next state

hw.next()
// { value: 'hello', done: false }
hw.next()
// { value: 'world', done: false }
hw.next()
// { value: 'ending', done: true }
hw.next()
// { value: undefined, done: true }

This is the basis of usage, had to introduce another point: next to the variable within the function by value

function* f() {
  for(var i = 0; true; i++) {
    var reset = yield i;
    if(reset) { i = -1; }
  }
}
var g = f();
g.next() // { value: 0, done: false }
g.next() // { value: 1, done: false }
g.next(true) // { value: 0, done: false }
The above code first defines a function f Generator can run indefinitely if there is no next method parameters, each run to yield statement, the value of the variable is always reset undefined. When the next method with a parameter true, the variable is reset to reset the parameters (i.e. to true), and therefore i is equal to -1, incrementing the next cycle will start from -1. This function is a very important grammatical meaning. Generator function to resume operation from the suspended state, its context state (context) is constant. Generator function after running, continue to inject the functions that value to the next parameter method, there is a way. That is, at different stages of operation Generator functions, different values ​​injection from the outside to the inside, thereby adjusting the behavior of the function. This used to achieve its usefulness in async / await crucial.

Guess you like

Origin www.cnblogs.com/junwu/p/11127764.html