What does star (*) mean in JavaScript function definition in Koa framework? [duplicate]
Asked Answered
T

1

19

I have been familiarising myself with Koa (http://koajs.com/). Many of the examples include star character in place of function name. For instance in the hello world example there is:

var koa = require('koa');
var app = koa();

app.use(function *(){
  this.body = 'Hello World';
});

app.listen(3000);

What does this star mean?

Thebes answered 2/5, 2014 at 7:55 Comment(2)
It's generator function. Check similar answer: https://mcmap.net/q/667907/-what-does-the-star-mean-in-function-definition-like-quot-function-quot-duplicateHemp
h3manth.com/new/blog/2014/getting-started-with-koajs Gives a nice explanation, it's called harmony:generatorsInstalment
L
16

It generally creates an "iterator" so you can yield result's one at a time.
Similar to C#'s yield key work.

Official Information

Example

The “infinite” sequence of Fibonacci numbers (notwithstanding behavior around 2^53):

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

Generators can be iterated over in loops:

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


  print(n);
}

Generators are iterators:

let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8
Leialeibman answered 2/5, 2014 at 8:0 Comment(6)
Hey that's kinda coolNagpur
This is awesome, thanks! Would you happen to know by any chance why the syntax is *? E.g. what is the reason you need to explicitly define that something is a generator? For instance in Python you don't need to do that.Thebes
Sorry, I have no idea..Leialeibman
While this is a 100% valid answer, still not clear what are generators used for in this very piece of code - why exactly do we need generator to assign this.body = 'Hello World?';Fielder
In Python I believe the presence of the "yield" operator is what determines if you have created a function or a generator. In Javascript this is explicit.Lunette
There's a good summary of Koa's use of generators at blog.stevensanderson.com/2013/12/21/…Lunette

© 2022 - 2024 — McMap. All rights reserved.