4

I have few functions, which calls another (integrated functions in browser), something like this:

function getItems () {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://another.server.tld/", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            items = $("a[href^=/courses/]", xhr.responseText);
        }
    };
    xhr.send();
}

As I don't want to write more code inside and make each logical functionality separated, I need this function to return variable items.

I know there can happen some accidents (network/server is not available, has long-response...) and the function can return anything after gets data from the server or timeout occurs.

1
  • 1
    I don't think a callback can return anything. :( Commented Feb 4, 2011 at 12:07

2 Answers 2

7

This seems be an async request. I don't think you will be able to return data from this function.

Instead, you can take a callback function as an argument to this function and call that callback when you have the response back.

Example:

function getItems (callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://another.server.tld/", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            callback(xhr.responseText);
        }
    };
    xhr.send();
}
Sign up to request clarification or add additional context in comments.

1 Comment

that's a nice idea, i thought there has to be a solution :-)
1

You're asking for synchronous requests: a function should not return until its return value can be computed even if this involves a hundred milliseconds of asking the server for the data.

By setting the third argument of xhr.open to true, you are using asynchronous requests — telling the browser that you want your function to return before the response from the server was received. Which pretty much means that it cannot return the items, since they have not been received yet.

Of course, using synchronous requests is an user interface pain, because your javascript is basically locked up until the response comes back a few hundred milliseconds later (if you're lucky).

What is advised is to correctly architecture your JavaScript code to account for asynchronous communications, and allow values to be returned through a callback instead of return. You don't have to, but it will save you a lot of pain in the end.

1 Comment

Having asked many questions here, I know from experience that answers like this where the responder does a lot of "handwaving" are often not helpful if they don't include actual code to demonstrate what's being said.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.