【发布时间】: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