I recently heard we are not suppose to using Synchronous behavior when using XHR. In my case I need Synchronous behavior. What is the best way to rewrite my calls to my services Synchronously instead of how I am doing it now. No jquery please ..
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/TestHtmlSend", false);
xhReq.send(null);
var serverResponse = JSON.parse(xhReq.responseText);
return serverResponse;
You never need “synchronous behavior”; instead, you (the developer) just have to wrap your head around JavaScript’s asynchronous nature – specifically, how to use anonymous callbacks and deal with closures.
For example, if you’re doing this:
It could be written asynchronously:
Notice in the asynchronous example that your inner callback function (which executes only after the network request has completed) still has access to the outer function’s
numbervariable. This is because JavaScript has static scope – in other words, when you declare a function, that function will permanently have access to the variables of any functions that enclose that function.