【问题标题】:AXIOS Async/Await How to best write the code?AXIOS Async/Await 如何最好地编写代码?
【发布时间】:2018-06-19 21:55:52
【问题描述】:

我正在使用 Axios、Mobx/Mobx 状态树 (MST) 和 Reactjs 编写我的第一个 ajax 调用。

在 MST 中,他们有一种叫做流的东西,基本上与 async/await 做同样的事情

 getCustomers: flow(function * (){
       const response = yield getEnv(self).axiosInstance.get("/Customers/Get");

       if(response.status === 200){
           // response.data
        } else {
             // error though not sure what the call is? response.error?
        }
}),

就这么简单吗?这是我应该如何检查状态是错误还是状态是否正常?

【问题讨论】:

    标签: reactjs async-await axios mobx-state-tree


    【解决方案1】:

    使用 mobx 流,future promise 的处理方式与 async/await 语法相同,成功的解析将作为结果返回,而失败的解析将导致抛出错误,等待被 catch 捕获陈述。您应该使用try / catch 来捕获错误。可以在此处找到有关此主题的更多信息:https://github.com/mobxjs/mobx-state-tree/blob/master/docs/concepts/async-actions.md

    对于您发布的示例代码,它还取决于您的端点如何处理错误以及它返回的状态代码。基本上,axios 将 200 响应视为成功,将其他 (400, 500) 视为失败。如果你的 API 遵循这个约定,你不需要检查 response.status 来查看是否响应成功,而是依赖 axios 为你做,示例如下:

    getCustomers: flow(function * (){
           try {
              const response = yield getEnv(self).axiosInstance.get("/Customers/Get");
              // Do something here if 200 response returned
           } catch (err) {
              // Error handling here when 500 returned
           }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2020-11-22
      相关资源
      最近更新 更多