0

I have 2 functions (setGame and loadScreen) that are related in the following way:

function setGame(user) {
  ajaxCall to server script that returns "res"
  as json object
  console.log(res.data.status);
  return res.data.status;
}

function loadScreen(user) {
  var gameStatus = setGame(user);
  if (gameStatus == 'WIN') {
    doSomething();
    console.log(gameStatus);
  } else if (gametStatus == 'NOWIN') {
    doSomeOtherStuff();
    console.log(gameStatus);
  } else
    showError(gameStatus);
}

The question is:

Why if I print in console the value of gameStatus in loadScreen(user), I get alwasy UNDEFINED, but if I print it in setGame(user) it shows the exact value that I am expecting?

It looks like a "sequence of execution" issue or something I cannot get to.

Any hint? Thank you very much.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Aptivus
  • 433
  • 1
  • 8
  • 24
  • Unfortunately you gave us *pseudo-code* for `setGame()` and not the actual implementation. This function fires an *asynchronous* request to the server, but, having done so, "JavaScript just keeps on going." It does not wait for the reply. If your actual implementation of `setGame()` *does* wait, you didn't show us exactly how it did so. Based on your description of what happens when you call `loadScreen()` I would conclude that it doesn't, and that would be your problem. – Mike Robinson Mar 04 '20 at 18:40
  • Thanks Mike. I have followed the leads posted in the suggested thread. I have written the code directly in the calling function, instead calling a function into another function – Aptivus Mar 05 '20 at 17:56

0 Answers0