How can I access the value yielded from inside a setTimeout?

我们两清 提交于 2021-01-28 14:50:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!