[英]axios promise value returns undefined in Chrome console and a string in Firefox console
[英]Axios prints value on console but returns undefined
一段时间以来,我遇到了一个很大的问题,并且感到不安,这没有任何意义。 我已经在我的React前端上使用了axios,当将get值分配给状态时,它可以完美地工作。 但是,当在普通的javascript代码中使用它时,我似乎遇到以下问题:我可以在控制台中打印对象的值,但它只会返回未定义的值。这是我的代码:
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。
您无法返回ajax响应,因为它是异步的。 您应该将函数包装为Promise或传递回调以登录
更新:正如@Thilo在评论中所说, async/await
是另一个选择,但是它可以让您设置对数据的响应,以便...
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
在ES7 / ES8中,您可以像老板一样进行异步/等待 :
login = () => {
return new Promise((resolve, reject) => {
axios.get('https://myaddress/authenticate')
.then(response => {
resolve(response)
})
.catch(error => {
console.error('auth.error', error);
reject(error)
});
});
};
async function getData() {
try{
const data = await login()
} catch(error){
// handle error
}
return data;
}
getData()
.then((data) => console.log(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.