There is a global variable var find; there is a function where I change the value of a global variable

 function getMe(){ data={action:'myInfo'}; $.post('core.php', data, function(response){ obj= JSON.parse(response); $.each(obj, function(key, value){ find = value['find']; }); }); } 

And if I call the function

 getMe(); console.log(find); 

then in the console undefined , why so?

  • one
    Because "asynchronous". console.log(find); runs before function(response){ ... } . - Igor
  • How to deal with it? ) setTimeout? - Alexander Reizan
  • Two ways: callback functions or Promises. - Dmitriy Simushev
  • There were already over 9,000 such questions. Here is one of them .

1 answer 1

Because the Ajax request went for processing, and the response received / processed will be after the execution of the current function

  • How to deal with it? ) setTimeout? - Alexander Reizan
  • @Alexander Reydzan do all your further actions in the function(response) callback. - Jean-Claude
  • It's easy to fight this - it's better to read in detail about what Ajax is and how to work with it in certain cases - SanŚ́́́́́́́́́́́́́́