react hooks中使用promise.all

发布时间 2023-08-27 13:25:20作者: IT小姐姐
useEffect(async () => {
    const getFirstResponse = async () => {
      try {
        return await axios.get('http://first-api', {
          params: { carId: id },
        });
      } catch (error) {
        return error;
      }
    };

    const firstResponse = await getFirstResponse();

    const getSecondResponse = async () => {
      try {
        return await axios.get('http://second-api', {
          params: { carName: firstResponse.data?.carName },
        });
      } catch (error) {
        return error;
      }
    };

    const secondResponse = await getSecondResponse();

    Promise.all([firstResponse, secondResponse])
      .then(function (values) {
        console.log(`values`, values);
      })
      .catch(function (err) {
        console.log(err);
      });

  }, []);