【问题标题】:How to return res from an API in the same order as how the calling function is looped?如何以与调用函数的循环方式相同的顺序从 API 返回 res?
【发布时间】:2021-06-14 11:03:35
【问题描述】:

我有一个根据用户输入更新的数组。

someArray = [a, b, c]

我想在遍历数组时获取 API

const arrayIWant = []
for ( var i=0; i<someArray.length; i++) {
    const arrayToString = []
    arrayToString.push(encodeURIComponent(someArray[i]))
    axios.get(`http://someURL&element=${arrayToString})
    .then(res => {
    arrayIWant.push(res.element)
})
}

它应该返回

arrayIwant = [d, e, f]

在哪里

d, e, f returned from a, b, c respectively. 

但是,我发现每次通过按钮调用提取请求时,提取请求中的 d、e、f 元素的顺序是完全随机的。我做错了什么?请帮忙。 提前谢谢你。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您可以使用Promise.all() 等待您的所有承诺解决并返回一个您想要的排序数组。

async function someFunc() {
  const callPromises = someArray.map((element) => {
    const arrayToString = [encodeURIComponent(element)];
    return axios.get(`http://someURL&element=${arrayToString}`);
  });

  return (await Promise.all(callPromises)).map((res) => res.element);
}

const arrayIWant = someFunc();

如果您不想使用async/await,可以执行以下操作

var arrayIWant = [];

const callPromises = someArray.map((element) => {
  const arrayToString = [encodeURIComponent(element)];
  return axios.get(`http://someURL&element=${arrayToString}`);
});

Promise.all(callPromises).then((responses) => {
  arrayIWant = responses.map((res) => res.element);
});

【讨论】:

  • 您好,Amr,非常感谢!我可以确认您的解决方案有效。很高兴我昨晚花了 3 个小时把头撞在墙上。我显然不应该跳过文件.....
猜你喜欢
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 2023-03-20
相关资源
最近更新 更多