Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: how to use generator and yield in a callback

Tags:

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?

like image 871
Xaree Lee Avatar asked Dec 26 '16 03:12

Xaree Lee


1 Answers

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));
like image 89
guest271314 Avatar answered Sep 28 '22 09:09

guest271314