-1

How would I return loadFile.responseText as the return value in xhr() function where loadFile.Open is set to true (async)... When I set the request as synchronous (false), the value is returned. I do understand why this happens but I am wondering if there is a way to accomplish this with asynchronous settings.

loadFile.open("GET", url, true); // no response

Whole function:

function xhr(url, async){

    var data = '';

    var loadFile = new XMLHttpRequest();

        loadFile.overrideMimeType("application/json");

        loadFile.open("GET", url, false); // when true, no value is returned (of course)

        loadFile.onreadystatechange = function() {

            if (loadFile.readyState === 4 && loadFile.status == "200")
            {
                data = JSON.parse( loadFile.responseText );

                return data;
            }
        }

        loadFile.send(null);

    return loadFile.onreadystatechange();
}

I was looking for an answer to this and found this How do I return the response from an asynchronous call? and it is NOT a duplicate.

I don't mind entirely changing the direction if it is required. Can you help with an actual basic example or a solid suggestion of which way to go to accomplish that?

Community
  • 1
  • 1
GRowing
  • 4,629
  • 13
  • 52
  • 75
  • If you already found the answer (that it is impossible what you are trying to do), what did you not understand about it? Did you try using a callback or a promise? Please show us your attempt or ask a more specific question, as otherwise we can't do more than to repeat the canonical. – Bergi Mar 02 '17 at 23:27
  • The question asked in the other thread is not the same. I am specifically asking how to go about doing that. Suggestions? An example of a callback or a promise? I am not looking to correct an error in the existing function. Do you have a suggestion or just a comment on the other thread? – GRowing Mar 02 '17 at 23:51
  • How to go about doing what? Returning a value from an asynchronous function? You cannot do that. Suggestions: use a callback or promises instead. Examples: [There](http://stackoverflow.com/a/30180679/1048572) are so many of them. – Bergi Mar 03 '17 at 00:08

1 Answers1

1

I am going to answer this then close this as a duplicate. This answer is purely a clarification for your SPECIFIC problem. The real answer is to read and understand the duplicate.

Here I'm going to copy and paste the relevant portion from the duplicate answer:

 var result = foo();
 // Code that depends on 'result'

becomes

 foo(function(result) {
     // Code that depends on 'result'
 });

So your code should be restructured as:

function xhr(url, callback){

    var data = '';

    var loadFile = new XMLHttpRequest();

        loadFile.overrideMimeType("application/json");

        loadFile.open("GET", url, false); // when true, no value is returned (of course)

        loadFile.onreadystatechange = function() {

            if (loadFile.readyState === 4 && loadFile.status == "200")
            {
                data = JSON.parse( loadFile.responseText );

                callback(data); //// NOTE: this is how you return the value
            }
        }

        loadFile.send(null);

    loadFile.onreadystatechange();
}

And how to use the returned result:

xhr(some_url, function (result) {
    // use result here

    // NO, it's not possible to get result outside this function
    // If you really want you can pass it further to other functions:

    do_something_with(result);

    // but you can NEVER return it
});

Basically you need to restructure your code and get used to callbacks.

There are fancier ways to do callbacks like promises and with newer versions of js async/await (which returns promises) but they're all callbacks nonetheless.

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • @Bergi: The answer is merely copy-pasted from the dup. I'd expect future searches to this to redirect to the dup. I don't think there's really anything new to add. This is a very specific clarification for the OP on how to specifically modify his code – slebetman Mar 03 '17 at 00:14
  • @GRowing Also relevant is this answer which may or may not be clearer than the one I marked as the duplicate: http://stackoverflow.com/questions/17460556/undefined-return-value-from-the-function-call-javascritpt/17460802#17460802 – slebetman Mar 03 '17 at 00:15
  • I appreciate the clarification @Bergi. Thank you. Would you suggest a well structured reading on XHR requests? – GRowing Mar 03 '17 at 00:19