18

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?

jsalonen
  • 29,593
  • 15
  • 91
  • 109
  • It's generator function. Check similar answer: http://stackoverflow.com/a/23285200/1140227 – George May 02 '14 at 08:00
  • 1
    http://h3manth.com/new/blog/2014/getting-started-with-koajs/ Gives a nice explanation, it's called harmony:generators – CoderDojo May 02 '14 at 08:01

1 Answers1

15

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
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • Hey that's kinda cool – Lightness Races in Orbit May 02 '14 at 08:10
  • 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. – jsalonen May 02 '14 at 09:05
  • Sorry, I have no idea.. – Amir Popovich May 02 '14 at 09:34
  • 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?'; – shabunc Jul 02 '14 at 09:47
  • 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. – Ryan Dec 21 '15 at 03:11
  • There's a good summary of Koa's use of generators at http://blog.stevensanderson.com/2013/12/21/experiments-with-koa-and-javascript-generators/ – Ryan Dec 21 '15 at 03:47