This is the 9th day of my participation in Gwen Challenge

Relearn JavaScript in a series of articles…

The Generator() function is another asynchronous programming solution for ES6. It is syntactically understood as a state machine that maintains several states internally and returns an object with an Iterator interface from which each state within a Generator() function can be retrieved in turn.

Simple usage:

Function * generator(){yield 'one' yield 'two'} let g = generator() "One ", done: false} g.ext () // Output: {value: "two", done: false} g.ext ()Copy the code

As you can see from the example, the Generator() function has the following properties:

  1. There is an asterisk (“*”) between the function keyword and the function name
  2. Internally, the yield keyword is used to define different internal states
  3. Generator() functions are not constructors and cannot use the new keyword by default, otherwise an error is reported and the internal this is invalid.
  4. After the Generator() function executes, the function body does not execute directly, but returns an object with an Iterator interface
  5. The body of the Generator() function is executed only after next() is called, and the yield keyword is paused. Of course, if a return statement is encountered, the whole function is terminated and all subsequent yield statements are invalidated.
  6. The next() function returns an object with both value and done attributes, with value representing the result of the yield expression
  7. When all yield statements are executed, the function is executed to the end. If there is a return statement, the expression of the return statement is returned as value. Otherwise, undefined is returned.

Here’s another example:

function* generator(){ yield 'one' yield 'two' return 'three' } let p = generator() for(let key of p){ console.log(key) // one two}Copy the code

The Generator() function returns an object with an Iterator interface, so you can use for… Of iterates, and the result is the return value of the yield expression.

How to make object type value traversal support for… Of it? Using the Generator() function, see an example:

Function * propGenerator(){let props = object.keys (this) for(let p of props){// Use yield to return an array of properties for each turn [p,this[p]] } } let obj = { a:1, B :2} obj[symbol.iterator] = propGenerator for(let [p,v] of obj){console.log(p+':'+v) {a:1 b:2}Copy the code

Finally, to look at the problem of nesting Generator() functions, yield* expressions can be used to support nesting, for example:

function* f1(){ yield '1' } function* f2(){ yield '2', Yield * f1() yield '3'} let f = f2() for(let k of f){console.log(k)}Copy the code

At this point, we’ve looked at another solution for asynchronous programming in ES6: the Generator() function.