【问题标题】:Bluebird: chain .then handlers in a loopBluebird:在循环中链接 .then 处理程序
【发布时间】:2016-03-16 07:35:58
【问题描述】:

问题:如何将getNextPaymentPayload/makePayment/confirmPayment 链接成一个循环?您可以随时使用hasAnyPayments 方法检查是否有任何付款。

问题:您不能并行付款。要进行付款,您需要等待前一笔付款完成。

示例:

SomeService
    //first payment
    .getNextPaymentPayload()
    .then(paymentPayload => this.makePayment(paymentPayload))
    .then(paymentResponse => this.confirmPayment)
    //second payment        
    .then(SomeService.getNextPaymentPayload())
    .then(paymentPayload => this.makePayment(paymentPayload))
    .then(paymentResponse => this.confirmPayment)
    //so on...

【问题讨论】:

  • hasAnyPayments 返回什么?
  • .then(getNextPaymentPayload)?
  • @Alnitak truefalse。如果false - 你应该停止付款,如果yes - 你应该至少再进行一轮getNextPaymentPayload/makePayment/confirmPayment
  • @elclanrs 你是对的。已更正
  • 那么hasAnyPayments是同步的,还是返回一个返回布尔值的promise?

标签: javascript promise ecmascript-6 bluebird


【解决方案1】:

假设 hasAnyPayments 将返回一个最终解析为布尔值的 Promise:

let doPayments = () => {
    return hasAnyPayments().then((hasAny) => {
        if (!hasAny) {   
            return Promise.resolve();        // all done
        } else {
            return SomeService.getNextPaymentPayload()
                      .then(paymentPayLoad => this.makePayment(paymentPayLoad))
                      .then(paymentResponse => this.confirmPayment(paymentResponse))
                      .then(doPayments);     // "recurse"
        }
    }
}     

【讨论】:

  • 似乎是最直接的答案
  • @bonebrigade 我自己最近一直在使用这样的代码。在我自己的代码中,我希望每次递归之间有 1 秒的延迟,所以我使用:return new Promise((resolve) => setTimeout(resolve, 1000) 而不是直接的Promise.resolve()
  • 你可以在 Bluebird 中使用 Promise#delay
  • @sdgluck 我实际上并没有使用 Bluebird - 上面的答案只是使用标准 Promises,没有任何扩展。
  • 你不需要return Promise.resolve()。你可以在那里做return;。无需创建额外的承诺。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2012-03-05
  • 2015-10-31
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多