我有一个递归方法,它本质上是递增一个值直到达到最大值。
increase(delay) {
return new Promise((resolve, reject) => {
if (this.activeLeds < this.MAX_LEDS) {
this.activeLeds++
console.log(this.activeLeds)
}
return resolve()
}).delay(delay).then(() => {
if (this.activeLeds < this.MAX_LEDS) {
this.increase(delay)
} else {
return Promise.resolve()
}
})
}
我正在测试一些功能,我想知道 increase()
方法何时完成(也称为解析)。
bounce(delay) {
return new Promise((resolve, reject) => {
this.increase(50).then(console.log('done'))
})
}
但是,当我在
之后解决 promise 时,我认为我做错了什么this.activeLeds < this.MAX_LEDS
不再正确。我认为这与我没有解决最初的 promise 但我不知道如何解决它有关。
最佳答案
您忘记从 then
回调中返回
递归调用的结果,因此无法等待它,并且 promise 将立即履行。
使用
increase(delay) {
if (this.activeLeds < this.MAX_LEDS) {
this.activeLeds++
console.log(this.activeLeds)
}
return Promise.delay(delay).then(() => {
if (this.activeLeds < this.MAX_LEDS) {
return this.increase(delay)
// ^^^^^^
}
})
}
顺便说一句,我建议避免在每次迭代中测试两次条件,并且即使在第一次调用时也立即停止而没有延迟:
increase(delay) {
if (this.activeLeds < this.MAX_LEDS) {
this.activeLeds++
console.log(this.activeLeds)
return Promise.delay(delay).then(() => // implicit return from concise arrow body
this.increase(delay)
)
} else {
return Promise.resolve()
}
}
关于javascript - 达到值后解决递归 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043855/