gpt4 book ai didi

javascript - 如何 promise 这个递归函数

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:43 25 4
gpt4 key购买 nike

下面是一个简单的递归函数,它接受一个长度,并使用 setTimeout 递减它。 .一旦长度为<= 0,完成。

如何编写此函数(使用纯 JavaScript)以便我可以像这样使用它:

animate(999).then(...)

const animate = length => {
console.log(length)
length -= 10
if (length <= 0) {
length = 0
return
}
setTimeout(() => {animate(length)}, 10)
}

animate(999)

更新:

这是我试过的。我遇到的问题是似乎resolve要么没有被调用,要么正在根据不同的 promise 被调用。

const animate = length => {
return new Promise((resolve, reject) => {
console.log(length)
length -= 10
if (length <= 0) {
length = 0
resolve(true)
return // without this the function runs forever
}
setTimeout(() => {animate(length)}, 10)
})
}

animate(999).then(result => console.log(result))

** 工作更新(但不理解)**

const animate = length => {
return new Promise((resolve, reject) => {
console.log(length)
length -= 10
if (length <= 0) {
length = 0
return resolve(true)
}
setTimeout(() => {resolve(animate(length))}, 10)
})
}

animate(999).then(result => console.log(result))

最佳答案

setTimeout(() => {animate(length)}, 10) 将不起作用,这可能会再次调用 animate 函数,但永远不会解析在中创建的 promise 最外层的调用(这是你的“工作更新”所修复的——它用递归调用的 promise 解决了外部 promise ,这将导致它们以相同的结果实现)。

与其乱搞回调,promisify您正在使用的异步原语,setTimeout:

function wait(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}

然后在你的动画函数中使用它来始终返回一个 promise :

const animate = length => {
console.log(length)
length -= 10
if (length <= 0) {
length = 0
return Promise.resolve()
}
return wait(10).then(() => {
return animate(length)
})
}

关于javascript - 如何 promise 这个递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42794051/

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