在将我定向到有关Promise.all或异步等待的先前答案之前,请先阅读查询。
我正在尝试使用Stripe API和Promises向许多卡收费。
如果收费成功,退款将发给其他客户。
收费金额取决于将要退款的机票价格。
某些收费会失败(客户的信用卡上没有足够的钱等),因此我需要等待下一次收费(承诺)是否成功,然后再转到下一个收费(承诺)。
我希望通过使用.then()中的拼接(如果成功)来确保使用正确的退款来计算费用,如果失败则不使用。
最后,我打算在使用代码完成所有费用后调用其他功能:
i===waitListToCharge.length-1
作为条件。
代码正在运行,但是promise似乎在之前的promise之前就已触发,并且条件在所有promise尚未完成之前就已触发-将错误发布到我的数据库中。我不明白为什么。
我最初尝试在while循环中使用一个promise,但是那也不起作用。代码概要在这里
解决此问题的最佳方法是什么?
let refundsCopy = ticketsToRefund.map(e => e)
waitListToCharge.forEach((e,i) => {
**code to calculate correct price and charges
let ChargeCard = stripe.paymentIntents.create({
***code to execute charge on stripe api
})
Promise.allSettled([ChargeCard])
.then(data => {
//if successful
if(data[0].status === 'fulfilled'){
successfulPayments.push(data[0])
refundsCopy.splice(0,e.quantity)
}else {
console.log('payment failed')
failedPayments.push(data[0])
}
if(i===waitListToCharge.length-1){
callOtherFunctions(successfulPayments,failedPayments,eventData,ticketsToRefund)
}
})
})
我尝试在其他人的建议下使用async等待,但是发生相同的问题。我使用的代码是:
async function testPromise(){
**code to calculate correct price and charges
let ChargeCard = stripe.paymentIntents.create({
}
)
let data = await Promise.allSettled([ChargeCard])
if(data[0].status === 'fulfilled'){
successfulPayments.push(data[0])
refundsCopy.splice(0,e.quantity)
}else {
failedPayments.push(data[0])
}
if(i===waitListToCharge.length-1){
callOtherFunctions(successfulPayments,ticketsToRefund)
}
}
testPromise()
})
更新:我通过基本编码自己的forEach循环来完成此工作。代码如下。有没有更简单的方法?
const myownForEachFunction = (e,i) => {
**code to calculate correct price and charges
let ChargeCard = stripe.paymentIntents.create({
***code for stripe
})
Promise.allSettled([ChargeCard])
.then(data => {
if(data[0].status === 'fulfilled'){
console.log('payment success')
successfulPayments.push(data[0])
refundsCopy.splice(0,e.quantity)
}else {
console.log('payment failed')
failedPayments.push(data[0])
}
if(i===waitListToCharge.length-1){
callOtherFunctions(successfulPayments,ticketsToRefund)
}else{
myownForEachFunction(waitListToCharge[i+1],i+1)
}
})
}
myownForEachFunction(waitListToCharge[0],0)