我正在尝试解决分散在数组内对象中的多个 promise 。这是我的代码的简单版本:
const getOrderSum = order_id => {
return new Promise(resolve => {
setTimeout(() => resolve(34), 1000)
})
}
const customer_array = [
{
customer_id: '19847743234730384',
name: 'Customer 1',
orders: [
{
order_id: '98749873244324',
price_per: 12
},
{
order_id: '9874987323545',
price_per: 16
}
]
},
{
customer_id: '123454351234123',
name: 'Customer 2',
orders: [
{
order_id: '918741433423',
price_per: 6
}
]
}
]
const result_array = customer_array.map(customer => {
const promises = customer.orders.map(async order => {
order.order_total = await getOrderSum();
return order;
});
customer.orders = promises;
return customer;
})
console.log(result_array);
在 map 循环内,我想调用一个异步函数,该函数为每个订单返回一个 order_total
。代码运行后 result_array
看起来像这样:
[
{
customer_id: '19847743234730384',
name: 'Customer 1',
orders: [ [Promise], [Promise] ]
},
{
customer_id: '123454351234123',
name: 'Customer 2',
orders: [ [Promise] ]
}
]
我如何一次解决所有这 3 个 promise 并得到这个:
[
{
customer_id: '19847743234730384',
name: 'Customer 1',
orders: [
{
order_id: '98749873244324',
price_per: 12,
order_total: 34
},
{
order_id: '9874987323545',
price_per: 16,
order_total: 34
}
]
},
{
customer_id: '123454351234123',
name: 'Customer 2',
orders: [
{
order_id: '918741433423',
price_per: 6,
order_total: 34
}
]
}
]
考虑到 Promise 不在一个数组中,我应该在哪里使用 Promise.all
?
最佳答案
- 将
customer_array.map
设为异步
。 - 将
await Promise.all
与customer.orders.map
结合使用,以便返回结果而不是Promise
。 - 由于我们已将
customer_array.map
设为async
,并且它没有包装在async
函数中,因此我们需要解决
使用Promise.all().then()
。在then
中写入所需的代码。
试试下面的方法。
const getOrderSum = order_id => {
return new Promise(resolve => {
setTimeout(() => resolve(34), 1000)
})
}
const customer_array = [{
customer_id: '19847743234730384',
name: 'Customer 1',
orders: [{
order_id: '98749873244324',
price_per: 12
},
{
order_id: '9874987323545',
price_per: 16
}
]
},
{
customer_id: '123454351234123',
name: 'Customer 2',
orders: [{
order_id: '918741433423',
price_per: 6
}]
}
]
const promises = customer_array.map(async customer => {
customer.orders = await Promise.all(customer.orders.map(async order => {
order.order_total = await getOrderSum();
return order;
}));
return customer;
});
Promise.all(promises).then(results => console.log(results));
关于javascript - 如何解决嵌套的promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65193295/