Axios在控制台上打印值,但返回未定义 [英] Axios prints value on console but returns undefined
问题描述
一段时间以来,我遇到了一个很大的问题,这让我感到不安,这没有任何意义.我已经在我的React前端上使用了axios,当将get值分配给状态时,它可以完美地工作.但是当在普通的javascript代码中使用它时,我似乎遇到以下问题:我可以在控制台中打印对象的值,但它只会返回未定义的值.这是我的代码:
I have quite an issue for some time and is getting on my nerves and it doesn't make sense. I have used axios on my react frontend and it works perfect when assigning the get value to the state. But when using it in a normal javascript code, I appear to have this following issue: i can print the object's value in the console but it will return only undefined.. Here is my code:
login = () => {
let data;
axios.get('https://myaddress/authenticate')
.then(response => {
data = response;
console.log('data here', data);
})
.catch(error => {
console.error('auth.error', error);
});
console.log('eee', data);
return data;
};
在这里,我们严格地谈论axios.
Here we are talking about axios strictly.
推荐答案
您无法返回ajax响应,因为它是异步的.您应该将函数包装为Promise或传递回调以登录
You can't return an ajax response because it's asynchronous. You should wrap your function into a promise or pass a callback to login
更新:正如@Thilo在评论中说的那样,async/await
是另一种选择,但是它可以让您将响应设置为...
UPDATE: As @Thilo said in the comments, async/await
would be another option, but it will let you set the response to data tho ...
1.兑现诺言
login = () => new Promise((resolve, reject)=>{
axios.get('https://myaddress/authenticate')
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
});
});
// Usage example
login()
.then(response =>{
console.log(response)
})
.catch(error => {
console.log(error)
})
2.传递回叫
login = (callback) => {
axios.get('https://myaddress/authenticate')
.then(response => {
callback(null,response)
})
.catch(error => {
callback(error,null)
});
};
// Usage example
login((err, response)=>{
if( err ){
throw err;
}
console.log(response);
})
3.异步/等待
login = async () => {
// You can use 'await' only in a function marked with 'async'
// You can set the response as value to 'data' by waiting for the promise to get resolved
let data = await axios.get('https://myaddress/authenticate');
// now you can use a "synchronous" data, only in the 'login' function ...
console.log('eee', data);
return data; // don't let this trick you, it's not the data value, it's a promise
};
// Outside usage
console.log( login() ); // this is pending promise
这篇关于Axios在控制台上打印值,但返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!