JS:如何在回调中使用生成器和yield
问题描述:
我使用JS生成器在回调中产生一个值 setTimeout
:
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 *
声明是同步的。你可以产生一个新的 Promise
对象,链 .then()
到 .next() .value
检索已解决的承诺
值
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(n))
.catch(e => console.error(e));