1. Synchronous expression of asynchronous operation
The effect of suspending execution of the generator function means that the asynchronous operation can be written in the yield statement and then executed later when the next method is called. This is actually equivalent to not having to write the callback function, because the subsequent operation of the asynchronous operation can be placed under the yield statement, anyway, wait until the next method is called to execute. Therefore, one of the important practical meanings of the generator function is to handle the asynchronous operation and rewrite the callback function.
function* Loadui () { showloadingscreen (); Yield loaduidataasynchronously (); Hideloadingscreen ();} var loader = Loadui (); // Load UI Loader.next () // Uninstalling UILoader.next ()
2. Control Flow Management
If you have a multi-step operation that is time consuming, using a callback function may be written as follows.
Step1 (function (value1) { function(value2) { function( VALUE3) { function(value4) { // do something with Value4 }); }); });});
Rewrite the above code with promise.
Promise.resolve (STEP1), then ( step2), then (step3), then (STEP4) .then (function (value4) { // do something with value4 function (error) {
// Handle any error from Step1 through Step4 }) . Done ();
The above code has changed the callback function into the form of a straight line execution, but added a lot of promise syntax. The generator function can further improve the code execution process.
function * Longrunningtask (value1) { try { var value2 = yield Step1 (value1); var value3 = yield Step2 (value2); var value4 = yield step3 (VALUE3); var value5 = yield step4 (value4); // do something with Value4 } catch (e) { // Handle any error from Step1 through STEP4 }}< /span>
3. Deploy iterator interface
With the generator function, you can deploy the iterator interface on any object.
function* iterentries (obj) { = Object.keys (obj); for (Let i=0; i < keys.length; i++) { = keys[i]; Yield [key, Obj[key]]; = {foo:3, bar:7 }; for (Let [key, value] of iterentries (MYOBJ)) { Console.log (key, value);} // Foo 3 // Bar 7
4. As a data structure
Generator can be thought of as a data structure, or, more precisely, as an array structure, because the generator function can return a series of values, which means it can provide an array-like interface to any expression.
From http://es6.ruanyifeng.com/#docs/generator# applications
The application of JS-ES6 learning note-generator function