如何访问setTimeout内部产生的值? [英] How can I access the value yielded from inside a setTimeout?
本文介绍了如何访问setTimeout内部产生的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
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 }
为什么要让 .next()
调用返回100?
Why should I do to have the .next()
call return 100?
推荐答案
您可能会考虑如下更改代码;
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.
这篇关于如何访问setTimeout内部产生的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文