解析javascript地图函数中的承诺



关于如何做到这一点,我已经问了几个问题和帖子,但没有一个有效。我已经尝试了一个数组(没有双关语)可能的解决方案涉及Promise.*,thenable,await和none都不起作用

我有一个从Prisma db调用中提取的付款数组,对象看起来像这样:

[{
"id": 1,
"amount": 100,
"payment_data": [{
"credits": 2,
"subscription_id": 534
}, {
"credits": 3,
"subscription_id": 469
}],
"customerId": 14
}]

我试图在每个payment_data下使用subscription_id运行另一个数据库查询,我为此构建了一个简单的函数:

const get_subscription = async function (subscription_id) {
return await db.subscriptions.findUnique({
where: {
id: Number(subscription_id)
}
})
}

然后我像这样在.map中执行它:

const mapped_payments = payments.map((payment) => ({
...payment,
payment_data: payment.payment_data.map(function (data) {
data.subscription = get_subscription(data.subscription_id).then((resp => resp))
return data
})
}))

问题是不管我怎么尝试都解决不了。如果我控制台日志mapped_payments,订阅对象显示为Promise {<pending>},并且在express中返回响应时完全为空。

我确信这是一个简单的解决方案,但我已经将所有可能的解决方案(Promise.*,thenable,await)移动到函数中,进入.map和res.send,但没有工作。

任何帮助都是感激的!

您需要使用async map callback来等待get_subscription函数,并且最好使用Promise.all来处理所有映射的承诺。

const mapped_payments = await Promise.all(payments.map(async (payment) => ({
...payment,
payment_data: await Promise.all(payment.payment_data.map(async function (data) {
data.subscription = await get_subscription(data.subscription_id)
return data
}))
})))