【问题标题】:Mapping async parallel requests to their IDs将异步并行请求映射到它们的 ID
【发布时间】:2019-10-09 20:44:24
【问题描述】:

所以我需要同时从多个来源获取数据,我的代码如下所示:

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。如何将返回的数据绑定到发起请求的数组元素?

【问题讨论】:

    标签: javascript ajax async-await axios


    【解决方案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);
    })();

    【讨论】:

      猜你喜欢
      • 2013-09-16
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2021-07-15
      相关资源
      最近更新 更多