promisejs.org
promisejs.org copied to clipboard
How can the "Fulfilling" section code work?
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?
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.