Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top