首页 > 解决方案 > 为什么我的 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))
})

标签: promisestripe-payments

解决方案


您的.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,
        });
     });

推荐阅读