Generator and Asynchronous Operation instance analysis in ES6, es6generator
This example describes the Generator and asynchronous operations in es6. We will share this with you for your reference. The details are as follows:
Generator and asynchronous operations
1. Generator Concept
Generator can be understood as a state machine (as if there are many States in React), encapsulating multiple internal states. The returned result of executing Generator is a traversal object that can traverse every state generated by Generator. Add * after the function to declare a Generator function.
function* hiGenerator(){yield 'hi';yield 'ES5';return '!';}var hi = hiGenerator();console.log(hi); //hiGenerator {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}console.log(hi.next()); //Object {value: "hi", done: false}console.log(hi.next()); //Object {value: "ES5", done: false}console.log(hi.next()); //Object {value: "!", done: true}
2. yield statement
Because the traversal object returned by the Generator function can be traversed to the next State only when the next () method is called, an execution function that can be paused is provided. When you execute next (), the yield statement is paused, and the value of the expression after yield is used as the value of the returned object. If you do not encounter yield, the return statement is used as the value of the returned object. If no return is returned, the value of the returned object is undefined.
3. next Method
The next () method can contain a parameter, which is treated as the return value of the previous yield statement.
function* add(c, d){var a = 0;a = yield a + c;a = yield a + d;return}var sum = add(1, 2);console.log(sum); //add {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}console.log(sum.next()); //Object {value: 1, done: false}console.log(sum.next()); //Object {value: NaN, done: false}console.log(sum.next()); //Object {value: undefined, done: true}
If you do not pass parameters to next (), the next calculation cannot be performed.
function* add(c, d){var a = 0;a = yield a + c;a = yield a + d + 1;return}var sum = add(1, 2);console.log(sum); //add {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}console.log(sum.next()); //Object {value: 1, done: false}console.log(sum.next(1)); //Object {value: 4, done: false}console.log(sum.next(3)); //Object {value: undefined, done: true}
4. Use for... of... to traverse Generator
When you use for... of... to traverse the Generator, you do not need to call the next () method.
5. After calling the return method for the traversal object ggenerated by a Generator function, the value Attribute of the returned object is the parameter of the return method.
6. Call another Generator function within a Generator function. Yield * is required *.
I hope this article will help you design the ECMAscript program.