简体   繁体   中英

Alternative Ways To Write XHR Synchronous Behavior

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:

function doSomething(arg) {
    var number = arg + 10; // for example
    var data = getDetail();
    data = JSON.parse(data);
    element.innerHTML = number + ': ' + data.name;
}

function getDetail() {
    var xhReq = new XMLHttpRequest();
    xhReq.open("POST", "ClientService.svc/REST/GetDetail", false); // bad!
    xhReq.send(null);
    return xhReq.responseText;
}

It could be written asynchronously:

function doSomething(arg) {
    var number = arg + 10;
    getDetail(function(data) {
        data = JSON.parse(data);
        element.innerHTML = number + ': ' + data.name;
    });
}

function getDetail(cb) {
    var xhReq = new XMLHttpRequest();
    xhReq.open("POST", "ClientService.svc/REST/GetDetail", true);
    xhReq.onreadystatechange = function() {
        if (xhReq.readyState == 4) cb(xhReq.responseText);
    }
    xhReq.send(null);
}

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 number variable. 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.

Usually it looks like this:

var xhReq = new XMLHttpRequest();
xhrReq.onreadystatechange = function() {
  if (this.readyState != 4) return;
  if (this.status != 200) ...process error...

  var serverResponse = JSON.parse(xhReq.responseText);
  ... process the response ...
}    
xhReq.open("POST", "ClientService.svc/REST/TestHtmlSend", true);
xhReq.send(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM