2

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?

1
  • 1
    The user experience effects of synchronous ajax are sufficiently negative as to make it a generally terrible idea. Commented Dec 3, 2013 at 0:31

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.