Bluebird:循环中的.then处理程序

时间:2015-12-10 15:29:03

标签: javascript promise ecmascript-6 bluebird

问题: 如何将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...

1 个答案:

答案 0 :(得分:3)

假设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"
        }
    }
}