【问题标题】:React Promise All Multiple APIs, Different Error HandlingReact Promise All 多个API,不同的错误处理
【发布时间】:2022-11-22 09:03:01
【问题描述】:

我想用 React Promise 运行不同的错误处理。一次运行所有 API 以节省时间,并且每个 API 都有不同的错误处理语句。如何才能做到这一点?

API 1 和 2 应该有不同的错误处理,即使一个 API 失败,每个 API 也应该继续。

参考:

Fetch API requesting multiple get requests

Promise.all([
            fetch(api1).then(value => value.json()),
            fetch(api2).then(value => value.json())
            ])
            .then((value) => {
               console.log(value)
              //json response
            })
            .catch((err) => {
                console.log(err);
            });

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    Promise.all 只是总结了你给它的任何承诺——所以你没有理由不能为每个错误单独处理。例如,您可以为每个提取创建一个单独的函数:

    const fetchFromApi1 = async () => {
      try {
        const response = await fetch(api1);
        return response.json();
    
      } catch (err) {
        console.log('API 1 failed');
    
        // You have to re-throw here if you want the promise returned by
        // this function to be rejected
        throw err;
      }
    };
    
    const fetchFromApi2 = async () => {
      // ----- 8< -----
    };
    

    然后你可以将它们组合到你的Promise.all -

    const fetchAllTheThings = async () => {
      try {
        const [response1, response2] = await Promise.all([
          fetchFromApi1(),
          fetchFromApi2(),
        ]);
    
      } catch (err) {
        // One of the promises was rejected
      }
    };
    

    【讨论】:

    • 在最后一个 catch 块上,如何区分来自 API1 的错误和来自 API2 的错误?我们的程序将需要不同的步骤
    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 2014-08-22
    • 2019-02-17
    • 2016-09-29
    • 2021-09-22
    • 1970-01-01
    • 2014-03-15
    • 2019-01-05
    相关资源
    最近更新 更多