Reactjs AXIOS Async/Await如何最好地编写代码?
我正在使用Axios、Mobx/Mobx状态树(MST)和Reactjs编写我的第一个ajax调用 在MST中,它们有一个称为流的东西,基本上与async/await做相同的事情Reactjs AXIOS Async/Await如何最好地编写代码?,reactjs,async-await,axios,mobx-state-tree,Reactjs,Async Await,Axios,Mobx State Tree,我正在使用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){
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?
}
}),
有这么简单吗?这就是我应该检查状态是否为and error或状态是否ok的方式吗?对于mobx flow,future promise的处理方式与使用
async/await
语法时相同,成功的解析将作为结果返回,而失败的解析将导致抛出错误,等待catch语句捕获。您应该使用try/catch
捕捉错误。有关此主题的更多信息,请参见:
对于您发布的示例代码,它还取决于端点如何处理错误及其返回的状态代码。基本上,axios
将200响应视为成功,将其他响应(400500)视为失败。如果您的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
}
})