JS: how to use generator and yield in a callback

Xaree Lee picture Xaree Lee · Dec 26, 2016 · Viewed 8.8k times · Source

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?

Answer

guest271314 picture guest271314 · Dec 26, 2016

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.log(n))
  .catch(e => console.error(e));