gpt4 book ai didi

javascript - JS : how to use generator and yield in a callback

转载 作者:可可西里 更新时间:2023-11-01 02:37:34 25 4
gpt4 key购买 nike

我使用 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*声明是同步的。您可以生成一个新的 Promise 对象,将 .then() 链接到 .next().value 以检索已解析的 Promise

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));

关于javascript - JS : how to use generator and yield in a callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41326217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com