javascript - 达到值后解决递归 Promise

标签 javascript recursion promise bluebird

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

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/

相关文章:

android - 递归使资源管理器变慢

javascript - 无法访问 for 循环中使用的链式 promise 内的外部作用域变量

javascript - 无法使用 webpack 将 Base64 图像导入到 React 组件中

javascript - AngularJS 中 undefined object 属性

java - 如何在Java中正确读取 "maze.txt"文件

python - python 中的指数退避实现

javascript - 为什么 Promise 构造函数如此冗长?

javascript - 为什么我的 Promise 数组在调用 Promise.all() 之前运行?

javascript - 我不断收到未终止的字符串文字错误

javascript - 只有一个类值发生变化