达到值后解决递归Promise

Resolve recursive Promise after value is reached

我有一个递归方法,它基本上递增一个值,直到它达到最大值。

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'))
    })
}

但是,我认为我在

之后解决承诺时做错了什么
this.activeLeds < this.MAX_LEDS

不再正确。我认为这与我没有解决最初的承诺但我不知道如何解决它有关。

您忘记了 return 来自 then 回调的递归调用的结果,因此无法等待它并且承诺会立即实现。

使用

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()
    }
}