我如何执行两个 Axios GET 请求,映射结果然后将其推送到数组?

How can I do two Axios GET requests, map the result and then pushing that to an array?

我很难理解 promises,在本例中是使用 Axios。我一直在阅读它并无休止地搜索 Whosebug,但仍然无法理解它。

首先,我尝试获取练习列表,结果中有一个 ID(称为 exercise_base)。我想使用该 ID 发出另一个 GET 请求以接收该练习的图像。

然后,我将名称、ID 和图像作为对象推送到数组。它非常适合获取练习列表并将其推送到数组,但在尝试获取图像时我似乎无法正常工作。

在我的对象中,我想传递从 getImages 承诺中收到的 imageUrl。我怎样才能做到这一点?

function getImages(exercise_base) {
  return axios.get("https://wger.de/api/v2/exerciseimage/?exercise_base=" + exercise_base);
}

const fetchData = async () => {
  const result = await axios(getFetchUrl());
  const array = [];
  // mapping through all the exercises, getting the exercise_base id which i then pass my getImages function
  result.data.results.map(({
    name,
    id,
    category,
    description,
    exercise_base
  }, e, index) => {
    getImages(exercise_base).then((e) => {
      // I want to pass this as imageUrl: in my object
      console.log(e.data.results[0].image);
    });
    array.push({
      value: name,
      description: "description",
      category: category,
      key: id,
      imageUrl: "" // Here I want to pass my imageUrl that I get from my getImages promise.
    });
  });
};

使用 Promise.all() 创建一个在所有内部承诺都解决时解决的单一承诺。每个inner promise的解析可以是完全水合的对象

const EXERCISE_IMAGE_URL = "https://wger.de/api/v2/exerciseimage/"

const getMainImage = async (exercise_base) => {
  const { data: { results } } = await axios.get(EXERCISE_IMAGE_URL, {
    params: { exercise_base } // using params is safer
  })

  // resolve with the first _main_ image (or undefined if none)
  return results.find(({ is_main }) => is_main)?.image
}

const fetchData = async () => {
  const { data: { results } } = await axios(getFetchUrl());

  // map each result to a new promise that resolves with the full object
  return Promise.all(results.map(async ({
    name,
    id,
    category,
    description,
    exercise_base
  }) => ({
    value: name,
    description,
    category,
    key: id,
    imageUrl: await getMainImage(exercise_base)
  })))
}