如何访问setTimeout内部产生的值?

时间:2016-08-06 17:36:53

标签: javascript generator

我有这段代码:

function* showValue() {
  setTimeout(function*() {
    console.log('yielding')
    return yield 100;
  }, 1000);
}

var valFunc = showValue();
console.log(valFunc.next());

当我运行它时,我看到了这个输出:

{ value: undefined, done: true }

我为什么要让.next()来电返回100?

1 个答案:

答案 0 :(得分:1)

您可能会考虑更改代码,如下所示;

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.