问题:如何将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将返回一个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"
        }
    }
}

10-07 14:06