51

Usually, I write code like this:

//definition
exports.getReply = function * (msg){
    //...
    return reply; 
}
//usage
var msg = yield getReply ('hello');

but how can I write and use a generator in and out of an es6 class? I tried this:

class Reply{
    *getReply (msg){
        //...
        return reply; 
    }
     *otherFun(){
        this.getReply();  //`this` seem to have no access to `getReply`
    }
}
var Reply = new Reply();
Reply.getReply();   //out of class,how can I get access to `getReply`?

I also tried:

 class Reply{
      getReply(){
         return function*(msg){
            //...
            return reply;
         }
      }
    }

All of these two methods seem to be wrong answers. So how can I write generator functions in a class correctly?

8
  • "All of these two methods seem to be wrong answers" --- what does it mean? You define generator functions in classes the same way the "normal" generator functions.
    – zerkms
    Aug 29, 2016 at 2:45
  • @zerkms Can you show an example? It creates a syntax error when I tried that.
    – 4castle
    Aug 29, 2016 at 2:48
  • 2
    Your code (the class definition in the first example) is syntactically correct and runs without syntax errors.
    – zerkms
    Aug 29, 2016 at 2:51
  • 1
    You need to use a different variable name, like var reply = new Reply();
    – 4castle
    Aug 29, 2016 at 2:55
  • 1
    @Bergi, this question is NOT a duplicate of the referenced question, this one is about classed and the other is about object literals Aug 29, 2016 at 3:02

4 Answers 4

57

Edit: Add more examples.
Your class definition is (almost) correct.The error was in instantiation var Reply = new Reply();. This tries to redefine variable assigned to class name. Also generator function is expected to yield something. I elaborated a little OP code to show working example.

class Reply {
  //added for test purpose
  constructor(...args) {
      this.args = args;
    }
    * getReply(msg) {
      for (let arg in this.args) {
        let reply = msg + this.args[arg];
        //generator should yield something
        yield reply;
      }
      //next call returns (yields) {done:true,value:undefined}
    }
    * otherFun() {
      yield this.getReply('Nice to meet you '); //yields Generator object
      yield this.getReply('See you '); //Yes, this can access 
      //next call yields {done:true, value:undefined}
    }
    * evenMore() {
      yield* this.getReply('I miss you '); //yields generator result(s)
      yield* this.getReply('I miss you even more ');
    }
}
//now test what we have
const reply = new Reply('Peter', 'James', 'John');
//let and var here are interchangeable because of Global scope
var r = reply.getReply('Hello ');
var msg = r.next(); //{done:false,value:"..."}
while (!msg.done) {
  console.log(msg.value);
  msg = r.next();
}
var other = reply.otherFun();
var o = other.next(); //{done:false,value:Generator}
while (!o.done) {
  let gen = o.value;
  msg = gen.next();
  while (!msg.done) {
    console.log(msg.value);
    msg = gen.next();
  }
  o = other.next();
}
var more = reply.evenMore();
msg = more.next();
while (!msg.done) {
  console.log(msg.value);
  msg = more.next();
}
//update of 1/12/2019
//more examples
for (let r of reply.getReply('for ')) {
  console.log(r);
}
for (let r of reply.evenMore()) {
  console.log(r);
}
//note that the following doesn't work because of lack of star (*) inside the generator function
for (let r of reply.otherFun()) {
  console.log(r);
}

UPDATE 1/12/2019

As suggested by @BugBuddy for..of loop looks even nicer (But doesn't work in all cases). See updated lines in the snippet.

5
  • Alex, I am wondering why you use yield this.getReply('Nice to meet you '); instead of yield * this.getReply('Nice to meet you'). The getReply itself is a generator function, isn't it ?
    – Seven
    Aug 30, 2016 at 11:16
  • Can you show the use of for...of in your example? Wouldn't that result in better code than the while loops?
    – BugBuddy
    Jan 12, 2019 at 5:46
  • 1
    @BugBuddy Thank you for suggestion and see updated answer. Jan 12, 2019 at 21:10
  • If you are interested, Symbol.iterator is one more thing you could add to your great example: Inside class Reply: *[Symbol.iterator]() { for (let a of this.args) {yield a;} } example use: for (let arg of reply) { console.log('I came from Symbol.iterator: ' + arg);}
    – BugBuddy
    Jan 13, 2019 at 0:29
  • Just a note, this does not work statically, i.e. static * getReply() {} is invalid, for this case (also works non-statically) use a getter, i.e. static get getReply() {return *function() {} }
    – Werlious
    Aug 5, 2020 at 7:38
49

TL; DR for confused visitors from Google:

In Javascript, how do I write a generator function in a class?

class A {
    * values() {
        yield "a value";
        yield* [1, 2, 3, 4, 5];
    }
}

is syntactically correct. It works. You’re welcome and now dismissed.

2
  • 🫡🫡🫡🫡🫡🫡🫡🫡 May 12 at 13:07
  • TypeScript: public* values() {}
    – Alec
    May 18 at 16:19
0

To add some documentation to the table:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*#generator_as_an_object_method

class Foo {
  *generator () {
    yield 1;
    yield 2;
    yield 3;
  }
}

const f = new Foo ();
const gen = f.generator();

console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }

-2

Generators are functions with a .next() for getting the yield'ed values or you can yield a generator function to let it know it doesn't need to "wait" upon encountering a yield statement for a .next to be called (reply.getReply().next(fn))

Your second piece of code is almost correct:

class Reply{
    *getReply (msg){
        //...
        return reply; 
    }
     *otherFun(){
        this.getReply();  //`this` seem to have no access to `getReply`
    }
}
var Reply = new Reply();
Reply.getReply();   //out of class,how can I get access to `getReply`?

First of all, please use const or let when working in ES6 and only use the uppercase variant for classes. You are trying to overwrite the class Reply statement with the var Reply = statement, which is not possible since the Identifier 'Reply' is already declared.

The answer you are looking for is as followed:
Just like you are doing in the first example, you should yield the generator functions, so your could should look like this:

class Reply{
    *getReply (msg){
        // yield something here, otherwise you should use a normal function
        return reply;
    }
     *otherFun(){
        const reply = yield this.getReply();  // yield the generator so it does what it needs to and doesn't wait for the .next() to be called on it
        return `${reply} within class ${this.constructor.name}`;
    }
}
const reply = new Reply();
const answer = yield reply.getReply('foo'); 
// getReply is a generator function, so it needs a `yield` or `.next()` to run beyond the first `yield` in the function
8
  • 2
    "you should yield the generator functions" - no. The code in your answer yields generators, and you shouldn't do that either. You should yield* generators.
    – Bergi
    Aug 29, 2016 at 8:02
  • "You are essentially overwriting the class Reply statement with the var Reply = statement." That's not possible. "const reply = yield this.getReply();" Why const reply = ? "yield reply.getReply('foo');" yield outside a generator function? Aug 29, 2016 at 10:33
  • @Bergi What do you mean with yield*? There is no such thing as yield*...? It's function *something(){} and yield... @zeroflagL I corrected the overwrite explanation, it'll actually return an error that the Identifier 'Reply' already exists. const reply = , because it's a new instance of Reply, so you might not want that to be overwritten bij something else and no, it's not possible to call yield to be called outside a generator function, but it is the way to do this. I'll change the answer to include more code on how to get the return value outside of a generator function
    – CherryNerd
    Aug 29, 2016 at 13:16
  • 1
    @CreasolDev Of course there is, look it up.
    – Bergi
    Aug 29, 2016 at 13:17
  • @Bergi Okay, my apologies, I did not know that, but if it's just the return value he wants, there is no reason to use yield* It would seem more logical to use something like co.wrap, which'll return a promise with the value wanted (outside of a generator)
    – CherryNerd
    Aug 29, 2016 at 13:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.