Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to use generators as class methods

My class looks like this:

class Test {
  constructor() {

  }

  *test() {
    console.log('test');
    let result = yield this.something();
    return result;
  }

  something() {
    console.log('something');
    return new Promise((resolve, reject) => {
      resolve(2);
    });
  }
}

But when I create an object from Test and call the test() method, I don't get the expected result ...

let test = new Test();
console.log(test.test()); // {}

Thought it would return 2.

Logs aren't shown as well.

What am I doing wrong here?

like image 307
Philipp Kyeck Avatar asked Sep 04 '26 05:09

Philipp Kyeck


1 Answers

It works properly. You need to call next() on returned value by test method.

let test = new Test();
console.log(test.test().next());

Output

test
something
{ value: Promise { 2 }, done: false } 

By calling test.test() you are creating new generator instance. Then you should call next() function on created instance to make generator yield value.

like image 113
pato Avatar answered Sep 05 '26 19:09

pato