【问题标题】:Reading response from async/await pattern in try/catch block从 try/catch 块中的 async/await 模式读取响应
【发布时间】:2021-11-16 10:47:21
【问题描述】:

我正在使用 try/catch 块中的 async/await 模式发出 API 请求..

async myRequest(data) {

  try {

    await api.post('/my-endpoint/', data).then((response) => { 

        console.log(response.data)
    });

  } catch (ex) {

     // WANT TO READ RESPONSE DATA HERE
  }
}

如果请求成功且没有错误,我可以使用.then() 方法读取response

如果请求失败,此 API 会返回一个 422 代码,触发 try/catch 异常。

但是,如果请求失败,此 API 仍会在响应正文中返回一些我想读取但无法读取的数据,因为触发了 catch 并且永远不会运行 .then()

如何从 catch 块中的异步函数获取响应正文?

【问题讨论】:

    标签: javascript ecmascript-6 async-await try-catch


    【解决方案1】:

    如果你想从一个 catch 块中检索响应数据,你可以从技术上做到这一点。

    见以下代码。

    const myRequest = async () => {
        try {
          const data = await fetch('https://jsonplaceholder.typicode.com/xxx/1').then((result)=> {
         
    
           // You can change the status code to 422 
           if (result.status === 404) {
             throw new Error('You can put your data here.')
             // Make sure the argument you passed in Error is a string 
           }
    
          return result.json()
        })
          
        } catch(e){
          console.log(e.message);
        }
    }
    
    myRequest()

    【讨论】:

      【解决方案2】:

      错误对象存储在ex 中,因此您可以使用以下命令记录错误 } catch (ex) { console.log(ex) } 您遇到的问题之一是在调用 API 之后放置 .then。当您使用 try-catch 块时,您不需要这样做,因为您可以将结果保存到变量中。

      try-catch 块的一个好处是可以处理错误并且您可以进行多次异步调用

      async myRequest(data) {
      
        try {
      
          const response = await api.post('/my-endpoint/', data)
          console.log(response.data)
        } catch (ex) {
      
           console.log(ex)
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-28
        • 2018-06-21
        • 1970-01-01
        • 2019-08-08
        • 2019-03-14
        • 2019-09-15
        • 2019-12-22
        • 2018-10-02
        • 2018-07-05
        相关资源
        最近更新 更多