Synchronous XMLHttpRequest deprecated

后端 未结 2 1440
萌比男神i
萌比男神i 2020-12-21 00:09

Today, I had to restart my browser due to some issue with an extension. What I found when I restarted it, was that my browser (Chromium) automatically updated to a new versi

2条回答
  •  礼貌的吻别
    2020-12-21 00:46

    This answer has been edited.

    Short answer: They don't want sync on the main thread.

    The solution is simple for new browsers that support threads/web workers:

    var foo = new Worker("scriptWithSyncRequests.js")
    

    Neither DOM nor global vairables aren't going to be visible within a worker but encapsulation of multiple synchronous requests is going to be really easy.

    Alternative solution is to switch to async but to use browser localStorage along with JSON.stringify as a medium. You might be able to mock localStorage if you allowed to do some IO. http://caniuse.com/#search=localstorage

    Just for fun, there are alternative hacks if we want to restrict our self using only sync:

    It is tempting to use setTimeout because one might think it is a good way to encapsulate synchronous requests together. Sadly, there is a gotcha. Async in javascript doesn't mean it gets to run in its own thread. Async is likely postponing the call, waiting for others to finish. Lucky for us there is light at the end of the tunnel because it is likely you can use xhttp.timeout along with xhttp.ontimeout to recover. See Timeout XMLHttpRequest This means we can implement tiny version of a schedular that handles failed request and allocates time to try again or report error.

    // The basic idea.
    function runSchedular(s)
    {
        setTimeout(function() {
            if (s.ptr < callQueue.length) {
                // Handles rescheduling if needed by pushing the que.
                // Remember to set time for xhttp.timeout.
                // Use xhttp.ontimeout to set default return value for failure.
                // The pushed function might do something like: (in pesudo)
                // if !d1
                // d1 = get(http...?query);
                // if !d2
                // d2 = get(http...?query);
                // if (!d1) {pushQue tryAgainLater}
                // if (!d2) {pushQue tryAgainLater}
                // if (d1 && d2) {pushQue handleData}
                s = s.callQueue[s.ptr++](s);
            } else {
                // Clear the que when there is nothing more to do.
                s.ptr = 0;
                s.callQueue = [];
                // You could implement an idle counter and increase this value to free
                // CPU time.
                s.t = 200;
            }
            runSchedular(s);
        }, s.t);
    }
    

提交回复
热议问题