What does `return function *(){...}` mean?

Javascriptnode.jsEcmascript 6

Javascript Problem Overview


I saw something strange in Koa. It has some new function names (from https://github.com/koajs/koa/blob/master/examples/co.js#L10):

app.use(function(){
  return function *(){
    var paths = yield fs.readdir('docs');

    var files = yield paths.map(function(path){
      return fs.readFile('docs/' + path, 'utf8');
    });

    this.type = 'markdown';
    this.body = files.join('');
  }
});

What does return function *() mean? Can we declare a function with the name of * in JavaScript?

Javascript Solutions


Solution 1 - Javascript

It means that the function returns an iterator (so it can be repeatedly called with .next() to yield more values.

check out http://wingolog.org/archives/2013/05/08/generators-in-v8 for more info

It's an ES6 construct, so at the moment you see it more in node rather than client side js

Solution 2 - Javascript

Koa makes use of a new JavaScript feature called generators, and the * is the way to identify a generator in V8.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAfshin MehrabaniView Question on Stackoverflow
Solution 1 - JavascriptbenjaminbenbenView Answer on Stackoverflow
Solution 2 - JavascriptLuc MorinView Answer on Stackoverflow