Return value from callback function

I have several functions that others call (built-in functions in the 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(); } 

Since I don’t want to write more code inside and share each logical functionality, I need this function to return variable elements.

I know that some accidents can happen (network / server is unavailable, has a long answer ...), and the function can return something after receiving data from the server or timeout.

+4
source share
2 answers

This seems to be an asynchronous request. I don’t think you can return data from this function.

Instead, you can take a callback function as an argument to this function and call this callback when you answer.

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(); } 
+5
source

You request synchronous requests: the function should not be returned until its return value has been calculated, even if it is associated with 100 milliseconds of server request for data.

By setting the third argument xhr.open to true , you use asynchronous requests - telling the browser that you want your function to return before a response is received from the server . Which pretty much means that it cannot return the elements since they have not yet been received.

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

It is recommended that you correctly configure JavaScript code to account for asynchronous messages and allow the return of values ​​through a callback instead of return . You do not have to, but in the end it will save you a lot of pain.

+2
source

Source: https://habr.com/ru/post/1338418/


All Articles