JS:如何在回调中使用生成器和yield [英] JS: how to use generator and yield in a callback

查看:311
本文介绍了JS:如何在回调中使用生成器和yield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use JS generator to yield a value in a callback of 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()

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

Why I can't yield values inside a callback in the generator?

推荐答案

function * 声明是同步的。你可以产生一个新的 Promise 对象,链 .then() .next() .value 检索已解决的承诺

function* declaration is synchronous. You can yield a new Promise object, chain .then() to .next().value to retrieve resolved Promise value

function* sleep() {
  yield new Promise(resolve => {
    setTimeout(() => {
      resolve(5);
    }, 5000);
  })
}

// sync
const sleepTime = sleep().next().value
  .then(n => console(n))
  .catch(e => console.error(e));

这篇关于JS:如何在回调中使用生成器和yield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆