Search code examples
javascriptcallbackyield

JS: how to use generator and yield in a callback


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?


Solution

  • 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));