简体   繁体   中英

how to simulate a synchronous ajax call? (synchronous based on asynchronous)

Since "native" synchronous ajax call blocks the browser user interface it doesn't fit most of real world cases (mine at least).

I'd like to know if there's any way to simulate a synchronous (blocking) ajax call, using an asynchronous (NON-blocking) ajax call , so that the result would be a synchronous call but without blocking the UI.

The following code explains it better:

function do_synchronous_ajax_call(url){
    // Performs an asynchronous ajax call, which doesn't block the UI, BUT, blocks this current script execution
}

var xyz = do_synchronous_ajax_call("http://...."); // Call is blocking until the inner ajax call returns
// Process `xyz` from here

As you see, the above wishes to have some sort of "synthetic" synchronous ajax call , which does NOT block the UI .

Javascript doesn't support multi-threading so that might be impossible, but worth asking.

This is the third question in the subject.
These questions followed me to the current question:
how to block on ajax call (I want it to block)
can a synchronous (blocking) ajax call block the browser's UI?

为了更新UI,需要将执行交还给浏览器,唯一的方法是通过异步代码(或立即返回的代码)

Why "block" something if you can simply do nothing instead? It seems like you actually don't understand asynchronous flow. You don't "wait" - you instead declare what to do when data is available. Set up your request with callback that will contain rest of your code, dispatch request and return from Javascript, leaving browser to do its own task until it is time for your code to work again.

You can set a globally available lock. Whether you're using a global variable or if you have an object set that holds any options or objects at a global level you can simply have a boolean lock.

function do_ajax_call(url)
{
    if (!locked)
    {
        // yadda yadda yadda
        locked = true;

        myxmlhttpobj.onreadystatechange = HandleCallback;
    }
}

function HandleCallback() {
    if (myxmlhttpobj.readyState==4 && myxmlhttpobj.status==200)
    {
         // more yadda yadda
    }

    locked = false;
}

If you switch to jQuery AJAX you will gain the benefit of a whole host of framework events and methods including "beforeSend" which would allow to you apply a similar locking mechanism in conjuction with the "done" event.

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