1

我有一个输入,我通过逗号 Ricky、Marty 等写下角色的名字。

因此,我对每个英雄都在数据库中提出请求并显示结果。

如果找不到英雄,如何显示成功和不成功请求的列表?

export const getServerSideProps: GetServerSideProps = async (context) => {

  const { name } = context.query;
  const nameArray = (name as string).split(',');

  const allRequest = nameArray.map((el) => axios.get(`https://rickandmortyapi.com/api/character/?name=${el}`));

  const charactersList = await axios.all(allRequest)
    .then(axios.spread((...response) => response.map((e) => e.data.results)));

  return ({
    props: {
      charactersList,
    },
  });
};

使用此代码,我只需从数据库中获取数据。我需要它

Ricky(来自输入的数据)---来自数据库的数据 Morty(来自输入的数据---来自数据库的数据)

等,但未找到其列表。

4

1 回答 1

0

您可能希望使用Promise.allSettled()等待所有承诺解决或拒绝(如果其中一个拒绝,请避免拒绝所有内容)。

export const getServerSideProps: GetServerSideProps = async (context) => {
    const { name } = context.query;
    const nameArray = Array.isArray(name) ? name : [name];

    const allRequest = nameArray.map((el) =>
        axios.get(`https://rickandmortyapi.com/api/character/?name=${el}`)
    );

    const charactersList = await Promise.allSettled(allRequest).then((res) => {
        // Iterate over all results, both successful or unsuccessful
        return res.map((result) => {
            // Returns response data if successful, or `undefined` otherwise
            // Handle this however you like
            return result.value?.data.results;
        });
    });
   
    //...
}

请注意,您应该避免使用axios.all/axios.spread因为它们已被弃用

于 2021-10-04T16:27:36.083 回答