How can the value requested in axios.get be used externally?

problem description

error using internally defined variable values outside the axios.get method. The value of
ipAddress is the current country code of ip, which I want to get from outside of the get method.
tried to define a variable to assign the entire axios.get method to it, but the result was a promise object.
also failed to use global variables. I don"t know if my code was written wrong

.

related codes

/ / Please paste the code text below (do not replace the code with pictures)

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)
}

when using the global variable method, the value of console.log (this.GLOBAL.ipAddress) is still the null value of ipAddress in App.vue, but every time I change the ipAddresses value in App.vue, the console outputs the correct value once, and then outputs the changed value. Ask for directions = = | |

Apr.15,2021

< H2 > in this way, you can use es7's async/await syntax sugar < / H2 >
let getIP = ''
try {
    (async () => {
        getIP = (await axios.get('http://ip-api.com/json')).data.countryCode
    })()
} catch (e) {
    console.log(e)
}
console.log(getIP)

the getIP is the value you need, not the Promise object, which looks something like this. You can see how async/await uses

.

the first time is that the request has not been completed yet. Even if the request of axios.get (' http://ip-api.com/json')) is completed in an instant, then the resolve function of this promise must be executed after console.log (this.GLOBAL.ipAddress), and the this.GLOBAL.ipAddress must be the initial value, that is, empty.


found that it is the reason for asynchronous data acquisition, and axios does not support data acquisition by Synchronize, and then switch to ajax. After solving the problem at that time, I forgot to close the problem

.
Menu