This code should send a request to the server and receive an object in which response.data is an array of numbers. In the first case (console.log (dataChart)), the array is normally output to the console, in the second case, undefined is displayed. What do Schaub does it work normally?

var dataChart; axios.get('https://xxxxxxxx.xx/handle.php?method=getStat') .then(function (response){ console.log(response); dataChart = response.data; console.log(dataChart); //N1! здесь нормально выводит массив }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed }); console.log(dataChart); //N2! undefined 

Reported as a duplicate at Grundy. javascript Apr 24 at 5:29 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • it works fine, console.log(dataChart); //N2! undefined console.log(dataChart); //N2! undefined console.log(dataChart); //N2! undefined is executed before dataChart = response.data; - Stranger in the Q
  • What is it like? can be a little more detailed - Ruslan
  • Have you heard about asynchronous functions? - Stranger in the Q
  • No, right now we'll take a look - Ruslan

1 answer 1

Anonymous function in your code:

 function (response){ console.log(response); dataChart = response.data; console.log(dataChart); //N1! здесь нормально выводит массив } 

asynchronous (they are also called callback ), a call to .then(...) does not lead to the execution of the function passed there, but somewhere inside stores a reference to it to call it later when the time comes (when the resource is loaded over the network) .

and the last line of console.log() is executed in the usual way. that is, immediately after the expression above it.