我使用 JS 生成器在回调中生成一个值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()
为什么我无法在生成器的回调中产生值?
function* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*声明是同步的。你可以产生一个新的Promise
物体、链.then()
to .next().value
检索已解决的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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)