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*
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With