我有一个简单的(我猜的)映射,用于具有多个 HTTP 请求的循环内的数组。在本例中使用 VUE 和 axios。
在第一个请求中,我获取了所有产品组,然后针对每个分销商,我进行了另一个调用。我有 6 个产品组和 32 个分销商。
axios.get('/product-groups').then((res) => {
res.data.forEach(pg => {
this.distributor.forEach(d => {
axios.get('/distributors/'+ d.id + '/product-data/' + pg.id).then((res) => {
res.data.product_group = pg.name;
this.pushToDataIn(res.data) //how this should look?
});
})
})
})
产品组是:
{
id: 1,
name: 'PG1'
}
结果 (res.data
) 是多个对象,如下所示:
{
comments: "Something"
distributor_id: 1
last_year: 250938.74
potential: 4549061.26
product_group: "PG1"
product_group_id: 107
}
现在,我想将此数据推送到基于 product_group
的数组,连接或添加一些属性(在同一产品组中)。
最佳答案
我不能 100% 确定您想要的最终结果,但为了至少解析数据,您可以从以下内容开始。那么将该数据映射到所需的格式应该不会太难。
技巧始终相同:将数据映射到 Promise 列表,然后await Promise.all(...)
。
// async fake product groups
// your: axios.get('/product-groups')
const getProductGroups = () => new Promise(resolve => {
setTimeout(resolve, 200, [
{ id: 1, name: 'PG1' },
{ id: 2, name: 'PG2' },
{ id: 3, name: 'PG3' },
{ id: 4, name: 'PG4' },
]);
});
// async fake distributor data
// axios.get('/distributors/'+ d.id + '/product-data/' + pg.id)
const getDistributorData = (dId, pgId) => new Promise(resolve => {
setTimeout(resolve, 200, [{
comments: "Something",
distributor_id: dId,
product_group_id: pgId,
}]);
});
(async () => {
// distributors are given
const distributors = [
{id: 1, name: 'Distributor 1'},
{id: 2, name: 'Distributor 2'},
{id: 3, name: 'Distributor 3'},
];
// await the product groups
const groups = await getProductGroups();
// map groups to promises
const groupPromises = groups.map(({id: pgId}) => {
// map distributors to promises
const distributorPromises = distributors.map(({id: dId}) => getDistributorData(dId, pgId));
// resolve
return Promise.all(distributorPromises).then(data => data.flat());
});
// await
const data = await Promise.all(groupPromises);
console.log(data);
})();
关于Javascript - 循环内多个 http 请求的映射数据(并按属性分组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021478/