Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "function*()" mean in nodejs? [duplicate]

I came across this idom: function* (){ ... } from this page https://github.com/jmar777/suspend and not sure what does it do.

Could anyone explain? Thanks!

like image 752
TLJ Avatar asked Feb 25 '14 03:02

TLJ


People also ask

How do you repeat a function in node JS?

You use repeating to print repeating strings: const repeating = require('repeating'); console. log(repeating(100, 'unicorn '));

What are generator functions?

Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function* syntax. When called, generator functions do not initially execute their code.

What does => mean in Nodejs?

basically means: app. post('/add-item', function(req, res) { // TODO: add an item to be posted }); The main difference between these two examples is that the first one lexically binds the this value. Follow this answer to receive notifications.

What does function * mean in JavaScript?

The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.


1 Answers

It means that the function is a generator function. Quoting from http://wiki.ecmascript.org/doku.php?id=harmony:generators#syntax

A function with a * token is known as a generator function.

Normal functions execute and return the result. But generators yield values and wait for them to get invoked again. Then the function will resume its execution.

Generator functions are normally iterated over. Since, they yield the values and wait from the next function call to resume execution, they are useful for infinite values generators.

They are memory efficient as well. For example, lets say you want to generate 10000000 numbers, if we store them in an Array, we might exhaust the machine's memory. But if we use a generator, we can generate one number, yield value and when called again execution will be resumed and the next number can be generated.

We can look at the examples, here,

function* fibonacci() {
    let [prev, curr] = [0, 1];
    for (;;) {    // Infinite looping
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

And as I said, generators are iterated like this

for (n of fibonacci()) {
    // truncate the sequence at 1000
    if (n > 1000)
        break;
    print(n);
}

See the generator function actually has an infinite loop. When yield curr is executed, value will be returned to n in n of fibonacci(). That is used in the iteration and when the generator is called again, it resumes the execution (it retains the data in variables as well) and generates the next element.

like image 124
thefourtheye Avatar answered Oct 03 '22 05:10

thefourtheye