Js-generator Foundation (Fourth week)
Read a few hours generator related articles, found that there are too many things, this week want to give up writing this, transliteration other aspects of the last time with this trick, but did not find other writable, and finally decided to write a fairly basic generator
What is generator?
- Generator is also to solve the hell callback problem, and last week's promise just like to achieve asynchronous programming, nature or a variety of callbacks;
At some point, you can think of generator as the newly defined data type in ES6, which is similar to a function, where each function can only return one result, that is, return only once, if you do not see return in some functions, In fact, in the end of the function there is a hidden return undefined, and generator different, you can return multiple
The principle of implementing asynchronous programming
- By way of a co-process, the process is that multiple threads work together to complete an asynchronous task, such as:
Use of generator
Generator Use function *, more than the normal function of a "*", generator in addition to the return statement, can be returned multiple times with yield, can also be seen as generator encounter yield is to return a value, and generator pauses in this, when the need to continue execution is only called generator.next () can continue execution, encountering yield and pausing, and then calling Generator.next () to continue execution ...
function*Gen(){Yield1;Yield2;Yield3;Yield4;Yield5;ReturnEnd;}Let G=Gen();Let I=0;Let St=SetInterval(()={Perform G.next () at 500ms per interval, execute 7 times, and print on console I++; Console.log (G.next (if (I>7) { Clearinterval }500
Results:
It can be seen that generator encounter Yleld will be paused, only if the call Generator.next () will be executed down, call this method will return {value:x, done:true/false}, this object value is the return value of yield, Done indicates whether the generator execution ends, and the done in this object becomes true only when executed to return, stating that execution is complete, and if it is still executed, such as the following two, do not execute until true.
< finish >
20180816
Play not widely
Js-generator Foundation