简体   繁体   中英

Pattern for synchronous/asynchronous AJAX function

I'm writing a function that's supposed to grab some JSON from another server, either synchronously or asynchronously depending on how it's invoked. In pseudo-code I have:

function getData(async, callback) {
    if (async) {
        // Get the data...
        return data;
    }
    else {
        // Get the data...
        callback(data);
    }
 }

It seems weird that the same function would either return a value or not... Am I violating any best practices here?

I don't see any point in having a single function that sometimes works async and sometimes not because the calling code HAS to know which it is doing and behave accordingly. May as well just have two functions then, one for sync and one for async that make the writing and understanding of the code much simpler.

In addition, the consequences for the user interface of doing any synchronous ajax call are generally bad so any good user experience design would pretty much always avoid synchronous ajax anyway.

If you were going to have only one function, then I'd suggest you give it an async design. Then the caller could write their code to the async style and it would work either way.

Also, you have your async logic backwards. It needs to call the callback when it's async.

function getData(async, callback) {
    if (async) {
        // get the data in async fashion
        doAjaxCall(function(data) {
            callback(data);
        });

    } else {
        // get the data synchronously
        callback(data);
    }
}

As an interesting reference, the jQuery ajax function is modeled this way. It has an asynchronous design that can be passed an argument to work synchronous in some circumstances.

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