我有一个根据用户输入更新的数组。
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. 但是,我发现每次我通过按钮调用fetch请求时,fetch请求中的d,e,f元素的顺序是完全随机的。我做错什么了?请帮帮忙。提前谢谢你。
发布于 2021-06-14 11:03:35
您可以使用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);
});https://stackoverflow.com/questions/67963703
复制相似问题