【问题标题】:Resolve recursive Promise after value is reached达到值后解决递归 Promise
【发布时间】:2017-11-01 04:24:42
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript recursion promise bluebird


【解决方案1】:

你忘记了 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()
    }
}

【讨论】:

  • 哇哦,这真的让我重新思考我对 Promise 的理解。很有意思。无论如何,它有效。会接受!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多