[英]Can't get value outside of Axios call
我希望您能解決axios遇到的問題。
我只是想在通話之外獲得價值,但我無法使其發揮作用。 這是一段小代碼:
axios.get('/api/get-user').then(({ data }) => {
this.user = data;
console.log(this.user); //returns the correct data
return this.user;
});
console.log(this.user); //returns null
這里發生了什么? 我也用let self = this
嘗試過,但是沒有用。 我希望你們能幫助我!
這是異步的問題,您正在axios請求完成之前調用console.log。 這就是為什么我們使用.then(res => {})的原因。
另一種選擇是使用異步等待。
用異步裝飾父函數
const myFunction = async() => {
const {data} = await axios.get('/api/get-user');
this.user = data;
console.log(this.user);
}
請參閱MDN以獲取更多信息,此鏈接是示例(我認為對理解最有幫助) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Examples
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.