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.
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:
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
totrue
, 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.