Discuss the use of Generator and Iterator in JavaScript, and generatoriterator

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.