Javascript - 循环内多个 http 请求的映射数据(并按属性分组)

标签 javascript arrays vue.js

我有一个简单的(我猜的)映射,用于具有多个 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/

相关文章:

javascript - 我如何使用 vue.js 通过 url 输入来调整我的一侧?

laravel - 如何在 Inertia.js 中操作浏览器 url?

vue.js - vue 语言服务器 : Elements in iteration expect to have 'v-bind:key' directives

javascript - 汇总.js : undefined objects in external dependencies

javascript - 傻瓜 setter/getter \ setter/getter

ios - 动态选择 UIPicker 行

ios - 如何检查通用 swift 数组包含一个元素?

javascript - jQuery 使用 on 方法将函数绑定(bind)到按钮

javascript - HTML 复选框无法使用 javascript 正确显示

arrays - 有没有更好的方法来处理可变大小的 slice ?