鍍金池/ 問答/HTML/ 在axios.get請(qǐng)求到的值怎么在外部使用?

在axios.get請(qǐng)求到的值怎么在外部使用?

問題描述

在axios.get方法的外部使用內(nèi)部定義的變量值時(shí)出錯(cuò)。
ipAddress的值是當(dāng)前ip所在的國家代碼,我希望能從get方法外部取到這個(gè)值。
試過定義一個(gè)變量將axios.get方法整個(gè)賦值給它,但是這樣得到的是一個(gè)promise對(duì)象。
用全局變量也沒有成功,不知道是不是自己代碼寫錯(cuò)了

相關(guān)代碼

// 請(qǐng)把代碼文本粘貼到下方(請(qǐng)勿用圖片代替代碼)

下面代碼得到的是promise變量
var getIP = axios.get('http://ip-api.com/json').then(function (response) {
    var ipAddress = response.data.countryCode
    console.log(ipAddress)
}).catch(function (error) {
  console.log(error)
})
console.log(getIP)

全局變量代碼
App.vue文件中:
<script>
    export default {
      name: 'App',
      created: function () {
      },
      ipAddress: ''
    }
</script>

event.vue文件中:
import _global from '../App.vue'
created: function () {
    Vue.prototype.GLOBAL = _global
    axios.get('http://ip-api.com/json').then(function (response) {
      _global.ipAddress = response.data.countryCode
    }).catch(function (error) {
      console.log(error)
    })
    console.log(this.GLOBAL.ipAddress)
}

使用全局變量方法時(shí)console.log(this.GLOBAL.ipAddress)的值還是App.vue中ipAddress的空值,但是每次我改變App.vue中ipAddress值的時(shí)候,控制臺(tái)會(huì)輸出一次正確的值,之后輸出的都是改變的那個(gè)值。求指點(diǎn) = =||

回答
編輯回答
蟲児飛

這樣,你可以使用es7的 async/await語法糖

let getIP = ''
try {
    (async () => {
        getIP = (await axios.get('http://ip-api.com/json')).data.countryCode
    })()
} catch (e) {
    console.log(e)
}
console.log(getIP)

這樣得到的getIP就是你需要的數(shù)值,而不是Promise對(duì)象,大致是這樣子的,你可以去看看async/await怎么使用

2017年1月31日 23:54
編輯回答
筱饞貓

發(fā)現(xiàn)是數(shù)據(jù)異步獲取的原因,而且axios不支持?jǐn)?shù)據(jù)同步獲取,然后換成ajax就好了,當(dāng)時(shí)解決之后忘記來關(guān)閉問題了

2018年1月7日 18:45
編輯回答
青裙

第一次是請(qǐng)求還沒有完成,就算axios.get('http://ip-api.com/json') 這個(gè)請(qǐng)求在瞬間完成了,那么這個(gè)promise 的resolve 函數(shù)肯定是在console.log(this.GLOBAL.ipAddress) 之后執(zhí)行的,此時(shí)this.GLOBAL.ipAddress 肯定是初始值,也就是空的。

2018年9月17日 07:59