promise - 为什么我的 promise.all 不返回数据,即使它有效
问题描述
我正在运行以下代码:
let Payment = relevantWaitList.map(e => {
stripe.paymentIntents.create({
amount: Math.round(e.totalCharge * 100),
currency: currency,
description: `Resale of ${eventData.title} refunded ticket`,
// customer: customerStripeID,
payment_method: e.paymentMethod,
off_session: true,
confirm: true,
application_fee_amount: Math.round(e.applicationFee*100)
}
,{
stripe_account: organiserStripeAccountID,
}
)
})
Promise.all(Payment)
.then(data => {
console.log('promiseall payment res', data)
}).catch(err => {
console.log('promise all payment fail', err)}
这将返回以下内容:
promiseall payment res undefined
尽管它返回未定义,promise.all 仍在工作 - 创建了条带支付意图。
当我更改承诺在地图中包含 .then 时(使用下面的代码),它控制台日志很好,但我更愿意在所有承诺完成后使用数据。
我错过了什么?
let Payment = relevantWaitList.map(e => {
stripe.paymentIntents.create({
amount: Math.round(e.totalCharge * 100),
currency: currency,
description: `Resale of ${eventData.title} refunded ticket`,
// customer: customerStripeID,
payment_method: e.paymentMethod,
off_session: true,
confirm: true,
application_fee_amount: Math.round(e.applicationFee*100)
}
,{
stripe_account: organiserStripeAccountID,
}
)
.then(data => console.log('data within map', data))
.catch(err => console.log('err within map', err))
})
解决方案
您的.map()
回调不返回任何内容,这意味着它.map()
只会返回一个 数组undefined
,不提供Promise.all()
任何承诺,也不提供要使用的数据。
您需要传递Promise.all()
的是一组承诺,每个承诺都解析为一个值,然后Promise.all()
将返回一个承诺,该承诺将解析为这些值的数组。在这种情况下,你有垃圾进入Promise.all()
,因此垃圾出来。
因此,您的.map()
回调应该返回一个解析为您最终想要的值的承诺。
假设stripe.paymentIntents.create()
返回一个可以解析为您想要的值的承诺,您只需要添加一个 return 语句:
let Payment = relevantWaitList.map(e => {
// ******* Add return on next line *********
return stripe.paymentIntents.create({
amount: Math.round(e.totalCharge * 100),
currency: currency,
description: `Resale of ${eventData.title} refunded ticket`,
// customer: customerStripeID,
payment_method: e.paymentMethod,
off_session: true,
confirm: true,
application_fee_amount: Math.round(e.applicationFee*100)
} , {stripe_account: organiserStripeAccountID,
});
});
推荐阅读
- python - 有没有办法将变量传递给 html 表单操作属性?
- swift - 同一个 UITableViewCell 中的两个标签约束
- encryption - 加密程序
- node.js - 如何使用不同的身份合并 Git 分支?
- go - Golang 解释 gdb SIGILL,非法指令
- cloudflare - 在长时间运行的脚本上防止 Cloudflare 524
- jquery - 单击行时将行单元格值作为单独的字符串获取
- c# - 如何用距中心的距离值来处理二维数组?
- python - 将具有不同名称的多个列堆叠到一个巨大的数据框中
- javascript - 如何使用本机 js 获取此表情符号 dec 表示?