Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the use of Generator function in js

Shulou Source: shulou.com Published: 2022-06-01 03:45:42 09月17日 Update

This article mainly shows you "what is the use of the Generator function in js", the content is simple and clear, and I hope it can help you solve your doubts, so let me lead you to study and learn "what is the use of the Generator function in js" this article.

What is the Generator function and what does it do?

The Generator function can be said to be the specific implementation of the Iterator interface. The most important feature of Generator is that it can control the execution of functions.

Function * foo (x) {let y = 2 * (yield (x + 1)) let z = yield (y / 3) return (x + y + z)} let it = foo (5) console.log (it.next ()) / / = > {value: 6, done: false} console.log (it.next (12)) / / = > {value: 8, done: false} console.log (it.next (13)) / = > {value: 42, done: true}

The above example is a Generator function, and let's analyze its execution:

First, when the Generator function is called, it returns an iterator.

When the first next is executed, the passing parameter is ignored and the function is paused at yield (x + 1), so 5 + 1 = 6 is returned.

When the second next is executed, the parameter passed in is equal to the return value of the previous yield, and if you do not pass the parameter, yield always returns undefined. At this point let y = 2 * 12, so the second yield equals 2 * 12 / 3 = 8

When the third next is executed, the passed parameters are passed to z, so z = 13, x = 5, y = 24, and the sum equals 42

Generator function generally does not see much, in fact, it has something to do with it, and will generally be used in conjunction with the co library. Of course, we can solve the problem of callback hell through the Generator function.

These are all the contents of the article "what is the use of Generator functions in js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Functions content articles parameters that is learning help maximum function can be through hell interface way easy to understand more organization features knowledge examples for the first time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB OPPO Reno vpn MySQL Redmi