AXIOS Async/Await 代码怎么写最好?
AXIOS Async/Await How to best write the code?
我正在使用 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?
}
}),
就这么简单吗?那是我应该如何检查状态是错误还是状态正常?
使用 mobx 流,未来的承诺处理方式与使用 async/await
语法相同,成功的解析结果将是 return,而失败的解析将导致抛出错误, 等待被 catch 语句捕获。您应该使用 try / catch
来捕获错误。有关此主题的更多信息,请参见此处:https://github.com/mobxjs/mobx-state-tree/blob/master/docs/concepts/async-actions.md
使用您 post 的示例代码,它还取决于您的端点如何处理错误以及它 return 的状态代码。基本上,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
}
})
我正在使用 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?
}
}),
就这么简单吗?那是我应该如何检查状态是错误还是状态正常?
使用 mobx 流,未来的承诺处理方式与使用 async/await
语法相同,成功的解析结果将是 return,而失败的解析将导致抛出错误, 等待被 catch 语句捕获。您应该使用 try / catch
来捕获错误。有关此主题的更多信息,请参见此处:https://github.com/mobxjs/mobx-state-tree/blob/master/docs/concepts/async-actions.md
使用您 post 的示例代码,它还取决于您的端点如何处理错误以及它 return 的状态代码。基本上,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
}
})