Synchronous vs Asynchronous - How do I even?

My game is fucked, because it relies solely on one function that is used everywhere and that function is now deprecated.

I don't understand how to make it work asynchronously.

Basically my function is Ajax but synchronous:

  1. ajaxRequest = function(param) {
  2.   var retrievedData = "";
  3.   var get_params = param;
  4.   var xhttp = new XMLHttpRequest();
  5.  
  6.   xhttp.onreadystatechange = function() {
  7.     if (xhttp.readyState == 4 && xhttp.status == 200) {
  8.       retrievedData = xhttp.responseText;
  9.     }
  10.   }
  11.  
  12.   xhttp.open("GET", "http://website.web/a.php" + "?" + get_params + "&rand=" + Math.random(), true);
  13.   xhttp.send();
  14.  
  15.   return retrievedData;
  16. };
Expand to see the code.


Such that I can use this function like so:


if (variable from web) == 1, do this
if (variable from web) == true, do that
Set (variable on web) to 7

Now I can do the third asynchronously, that's fine. But the first two require a response immediately, and I don't want or need the game to continue in that time.

For example, game switches is replaced with this function, so when a switch is used I do something like this (but with error handling and such):

  1. get_switch = function(t, variable) {
  2.   $return = ajaxRequest("a=gs&t=" + t + "&i=" + variable);
  3.   return $return;
  4. }
Expand to see the code.


conditonal branch: script: {
get_switch(1);

}


Now that they're saying is that I have to handle this asynchronously instead. Now that doesn't make sense in the context of a conditonal branch.

Say I have a chest. I want to find out if the chest has been opened, so I ask the server (get_switch(1)). I don't want or need the script to continue processing until the response comes through, because I need the value for the rest of the script to make any kind of sense.


But I can't do this synchronously any more.

I don't even understand how this is supposed to work. I guess the answer is it doesn't?

Isn't this going to kill a lot of online games?
Hacky way: load the switch states on map load and poll the server for it every now and then
Proper way: provide callbacks to your jquery ajax calls (ie. success) to continue the code after the call instead, typically done using anonymous functions

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=80519