【问题标题】:JS: how to use generator and yield in a callbackJS:如何在回调中使用生成器和产量
【发布时间】:2017-05-10 14:55:15
【问题描述】:

我使用JS生成器在setTimeout的回调中产生一个值:

function* sleep() {
  // Using yield here is OK
  // yield 5; 
  setTimeout(function() {
    // Using yield here will throw error
    yield 5;
  }, 5000);
}

// sync
const sleepTime = sleep().next()

为什么我不能在生成器的回调中产生值?

【问题讨论】:

    标签: javascript callback yield


    【解决方案1】:

    function* 声明是同步的。您可以生成一个新的Promise 对象,将.then() 链接到.next().value 以检索解析的Promise

    function* sleep() {
      yield new Promise(resolve => {
        setTimeout(() => {
          resolve(5);
        }, 5000);
      })
    }
    
    // sync
    const sleepTime = sleep().next().value
      .then(n => console.log(n))
      .catch(e => console.error(e));
    

    【讨论】:

    • 这只解析一次,所以它不会产生太多:) 例如,代码如何从setInterval 回调中重复yield
    • .then(n => console(n)) 应该是.then(n => console.log(n))
    • 只产生一次的生成器有什么意义?
    • 这对我有用。我需要一个生成器来为执行 ADB exec-out 的生成进程生成一次。在进程完成执行后,我从管道中捕获了标准输出。然后我用字符串产生解决承诺。对于这种类型的使用来说就像一个魅力:)
    • > 只产生一次的生成器有什么意义? -> 浏览器兼容性
    猜你喜欢
    • 2019-10-12
    • 2016-05-20
    • 2018-12-21
    • 2017-05-17
    • 2014-09-17
    • 2015-06-26
    • 2020-04-23
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多