代码之家  ›  专栏  ›  技术社区  ›  Geo

如何访问从setTimeout内生成的值?

  •  1
  • Geo  · 技术社区  · 8 年前

    我有这个代码:

    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 回复  |  直到 8 年前
        1
  •  2
  •   pinkwaffles    6 年前

    您可能会考虑如下更改代码:;

    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.