0

I have defined a variable myData outside a function and I try to assign the data which I get from axios to the variable myData, but failed. The variable shareData has the right value -- response.data inside the function -- but the value of it turned to the original one when exiting the function.

It must be the local variable covers the outer one, so how do you avoid this and let the outer variable get the response.data value?

var shareData = 'OUTSIDE THE FUNCTION'

axios({
    method: 'get',
    url: '/api/usershare', //API
    responseType: 'json',
  })
  .then(function(response) {
    shareData = response.data
    console.log(shareData) //output the reponse.data correctly
  })
console.log(shareData) //output OUTSIDE TEH FUNCTION, which is the orignal value of myData
freginold
  • 3,946
  • 3
  • 13
  • 28
  • 1
    More like why is an asynchronous function not acting like it is synchronous. You order a delivery pizza and as soon as you click submit on the order form you try to eat the pizza. – epascarello Oct 25 '17 at 13:23
  • Try this my answer on https://stackoverflow.com/questions/46885012/call-a-global-variable-into-two-functions-using-javascript/46885947?noredirect=1#comment80729697_46885947 – Nisal Edu Oct 25 '17 at 13:25
  • 4
    use `promise` or `setTimeout` instead.because this is asynchronous code it will execute last `console` it won't `wait` for your `axios request` to complete – Ashish Yadav Oct 25 '17 at 13:26
  • 1
    @ashishyadav : Promise is best setTimeout fails many times or unnecessary waste of time. – Niklesh Raut Oct 25 '17 at 13:28
  • @user2486 you are absolutely right. I was just giving lucasFang a quick explanation and solution – Ashish Yadav Oct 25 '17 at 13:30

0 Answers0