Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can the "Fulfilling" section code work? #31

Open
iandanforth opened this issue Oct 1, 2015 · 1 comment
Open

How can the "Fulfilling" section code work? #31

iandanforth opened this issue Oct 1, 2015 · 1 comment

Comments

@iandanforth
Copy link

function* demo() {
  var res = yield 10;
  assert(res === 32);
  return 42;
}

var d = demo();
var resA = d.next();
// => {value: 10, done: false}
var resB = d.next(32);
// => {value: 42, done: true}
//if we call d.next() again it throws an error

demo takes no arguments, and doesn't assign any values out of arguments so how could the second call to demo.next() possibly pass the assert(res === 32); line?

@ForbesLindesay
Copy link
Owner

The * after function indicates that demo is a generator function. What that means is that calling demo doesn't actually evaluate the function, it just sets up a new context for the function. When you first call d.next() it actually begins executing the function, but pauses when it gets to the first yield keyword. The second call, d.next(32) passes 32 in as the result of the yield expression. This causes the assertion to pass and the demo function to continue the rest of its execution. It's this ability to pause execution of the function that makes generator so powerful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants