[英]Using async await with axios
我有一个 function 调用 axios 并返回它:
const makeRequest = () => {
return axios.get('/data');
}
const printResponse = () => {
makeRequest()
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
我正在尝试使用 async await 来改善这一点并避免使用“then”。
const makeRequest = async () => {
return await axios.get('/data');
}
const printResponse = () => {
try {
const response = makeRequest();
console.log(response)
} catch(error) {
console.log(error)
}
}
然而,尽管使用await
, makeRequest
仍然返回 promise,所以无论如何我必须在我的printResponse
function 中使用then
。 我没有正确使用它吗?
“然而,尽管使用await
, makeRequest
仍然返回一个承诺”
是的,当然可以。 async/await
只是使用 Promises 的语法糖。 特别是,任何标记为async
的 function 将返回 Promise - 这是设计使然。
如果你不喜欢使用.then
,你可以很容易地使用async/await
来使用这个 promise:
const printResponse = async () => {
try {
const response = await makeRequest();
console.log(response)
} catch(error) {
console.log(error)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.