[英]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.