1
var someVariable;

axios
  .get(
    `example.com`
  )
  .then((result) => {
    someVariable = 1;
    console.log(someVariable);
    // Prints 1
  });

console.log(someVariable);
// Prints undefined

Why does it keep printing undefined even tho I changed variable

General Grievance
  • 4,555
  • 31
  • 31
  • 45
YooobY
  • 11
  • 1
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – John Montgomery Jul 28 '21 at 01:43

1 Answers1

0

Because that's how variable scopes and promises work in JavaScript. 'someVariable' only lives within the callback and function and is supposed to do so since it is an async operation, so there is no reason to use it outside the callback as you did in the code snippet.

It remains undefined as you declared it outside the function.

I suggest you read documentation about how promises work and eventually how to handle them using async/await.

  • anyways to implement this? – YooobY Jul 28 '21 at 00:16
  • It depends on what your final goal is. Since axios.get is an async operation, you don't know when it is going to fire, so there is no point in expecting someVariable to be 1 outside the function you pass as an argument to .then(). The difference is that, while the console.log inside .then() will surely happen after someVariable = 1, the console.log at the end at the end of the snippet will most probably fire when someVariable is still undefined. – Jadus29 Jul 28 '21 at 12:09
  • i have tried everything and nothing seems to work for me, i tried calling a function when axios is done, but again i need variable outside of a specific function so i can return it when i need it – YooobY Jul 28 '21 at 14:14