Discuss the use of Generator and Iterator in JavaScript, and generatoriterator
When it comes to Generator, we will talk about topics such as Asynchronization. This is obviously broken by some strange things. Iterator should be closely related to Generator. Using Generator to process Asynchronization may be something C # programmers will think. Of course, this method does have a complete set of things, but I personally don't like it.
The only difference between Generator and Asynchronization is the next call time. Because next can be called asynchronously, Generator can be abused asynchronously.
However, I think the next method can be called asynchronously, but the correct method of use should be synchronous. At least when a Generator instance is used for the for-of loop or [... obj] deconstruct, it continuously calls next.
In addition to the asynchronous problem of next, the parameter of next is also a problem. Since the parameters passed in the next call will be used as the return value of the yield operator, generator has a richer usage method. In earlier versions of python, yield was a statement rather than an operator. In later versions, yield was used as an operator, so various pitfalls occurred.
When the Generator instance is used as an Iterator, neither the next call nor the next parameter will be passed in asynchronously. I think this is the correct usage of Generator. In other words, Generator is used to implement Iterator. At least the name of Generator has no other meaning. The following is an example:
Run
<Script> var match = function * (pattern, string) {var regexp = new RegExp (pattern, 'G'); for (let I; I = regexp.exe c (string ); yield I) ;}; for (let I of match ('A', 'abcabcabc') {console. log (I) ;}</script>