将异步并行请求映射到其ID

时间:2019-10-09 12:23:53

标签: javascript ajax async-await axios

所以我需要同时从多个来源获取数据,我的代码看起来像这样:

myArray = [
    {
        id: 987447,
        url: http://someurl.com/data1.json
    },
    {
        id: 923473,
        url: http://someurl.com/data2.json
    },
]

async function getData(myArray) {
    let data = await Promise.all(
        myArray.map(a => axios.get(a.url))
    )
    // console.log(data);
}

..但是,问题在于,一旦提取数据,它就与myArray中的ID没有任何链接,因此我不知道哪个对象属于哪个id。如何将返回的数据绑定到发起请求的数组元素?

1 个答案:

答案 0 :(得分:1)

Promise.all返回的数据与您赋予它的Promises相同。

const arr = [{
  url: 'URLA',
}, {
  url: 'URLB',
}, {
  url: 'URLC',
}];

async function funcAsync(url) {
  return url;
}

(async() => {
  const ret = await Promise.all(arr.map(x => funcAsync(x.url)));

  console.log(ret);
})();


如果要在返回的数据和原始数组之间建立对应关系,可以使用数据的位置,例如:

const arr = [{
  url: 'URLA',
}, {
  url: 'URLB',
}, {
  url: 'URLC',
}];

async function funcAsync(url) {
  return url;
}

(async() => {
  const ret = await Promise.all(arr.map(x => funcAsync(x.url)));

  const correspondance = ret.map((x, xi) => ({
    ...arr[xi],

    result: x,
  }));

  console.log(correspondance);
})();