3

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?

5
  • What is the expected result? Commented Nov 30, 2016 at 13:41
  • Try console.log(Array.from(test.test())). Commented Nov 30, 2016 at 13:59
  • @Cerbrus 2 - added that to the question Commented Nov 30, 2016 at 14:23
  • Have a look at MDN - Generators to refresh your memory about generators. Commented Nov 30, 2016 at 15:11
  • @FelixKling was using coroutines for too long - expected their behavior to be the default generator behavior ;) Commented Dec 8, 2016 at 12:53

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.