我是个新手,我想根据函数参数发出一个Axios.get()请求。这就是我尝试过的。
const mentorName = (value) => {
try {
Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
).then(res => {
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
}
})
} catch (error) {
console.log(error)
}
}但它不起作用,因为在控制台中没有打印res。这里面有什么问题呢?
运行良好的代码是:
const mentorName = (value) => {
try {
const res = Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
)
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
}
} catch (error) {
console.log(error)
}
}下面的代码运行良好,但返回了封装在promise中的信息。现在如何访问它,因为res.data不是有效的属性。
发布于 2021-04-29 18:25:15
你能在async/await上试试这个吗?
import axios from 'axios';
const mentorName = async value => {
try {
const res = await axios.get(`${BASE_URL}/api/v1/consultations/${value}`);
console.log(res);
} catch (error) {
console.log(error);
}
};在console.log inside try块中,您可以检查api response。
发布于 2021-04-29 18:36:36
const mentorName = (value) => {
try {
Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
).then(res => {
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
}
})
} catch (error) {
console.log(error)
}
}由于if条件,上面的代码不会打印,很可能大部分时间状态都是200,而200以外的任何值都会向下钻取到catch块
它在下面的代码中打印promise的原因是,它是一个等待实现的promise,并且您设置的比较/条件非常好,因为res是promise,而res.status是未定义的
const mentorName = (value) => {
try {
const res = Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
)
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
}
} catch (error) {
console.log(error)
}
}调整代码以包含else块,您可以始终在控制台中看到打印的内容
const mentorName = (value) => {
try {
Axios.get(
`${BASE_URL}/api/v1/consultations/${value}`
).then(res => {
if (res.status !== 200 || res.data.status !== "success") {
console.log(res)
return
} else {
console.log(res);
}
})
} catch (error) {
console.log(error)
}
}我不建议使用async/await,因为有一个紧迫的原因,那就是UI线程会被搁置,直到异步调用得到解决。只是为了让它看起来像一个同步调用。坚持承诺之道。
https://stackoverflow.com/questions/67314874
复制相似问题