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 wi
Solution 1:
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));
Post a Comment for "Js: How To Use Generator And Yield In A Callback"