问题
I have this code:
function* showValue() {
setTimeout(function*() {
console.log('yielding')
return yield 100;
}, 1000);
}
var valFunc = showValue();
console.log(valFunc.next());
When I run it, I see this output:
{ value: undefined, done: true }
Why should I do to have the .next()
call return 100?
回答1:
You might think about changing the code as follows;
function showValue() {
return setTimeout(function() {
function* gen() {
console.log('yielding');
yield 100;
};
var it = gen();
console.log(it.next().value);
}, 1000);
}
showValue(); // will display result after 1000+ms
console.log(showValue()); // will immediately display setTimeout id and after 1000+ms will display the generator yielded value again.
来源:https://stackoverflow.com/questions/38807028/how-can-i-access-the-value-yielded-from-inside-a-settimeout