-1

I'm trying to return the result of an XMLHTTPRequest:

<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">Click me for Google CDN jQuery!</a> 

<script>
    const url = {
        httpRequest: function(callback) {
            var xhr = new XMLHttpRequest();
            xhr.addEventListener("load", callback);
            xhr.open("GET", document.querySelector("a").href); // Using querySelector to simulate how my real program works - I don't want to hardcode anything mainly because this should be dynamic.
            xhr.send("");
        },
        compileData: function(data) {
            var response = data.target.responseText.substring(4, 17) 
            // I can't figure out how to take this response and 'return' it.
        },
        getContent: function() {
            url.httpRequest(url.compileData)
        }
    }

     var content = url.getContent() // I want 'content' to be equal to "jQuery v3.3.1"
</script>

But, I can't figure out how to 'return' the response.

Yes, I know that there are other questions out there like this one, namely: How do I return the response from an asynchronous call? But, I'm new to JavaScript and have no idea how to integrate what they're saying there into my case.

3 Answers3

0

A few options for applying the guidance given in "How do I return the response from an asynchronous call?"

  1. If you'd like to continue using callbacks, then it's a matter of adding another. The result you'll want is to allow your entry point to accept its own:

    url.getContent(function (content) {
      // proceed with `content` here
    });
    

    So, getContent needs to expect the argument:

    getContent: function(callback) {
      // ...
    }
    

    But, it also needs to call the callback, which it can do with yet another intermediate function, so it can combine callback with compileData:

    getContent: function(callback) {
      url.httpRequest(function (data) {
        callback(url.compileData(data));
      });
    }
    
  2. You can also use Promises throughout the url object.

    Starting with httpRequest, you can utilize jQuery.ajax() and its shortcuts returning a customized promise object – a jqXHR:

    httpRequest: function () {
      return Promise.resolve(
        jQuery.get(document.querySelector("a").href)
      );
    }
    

    In this, Promise.resolve() can be used to convert the customized promise into a standard Promise.

    Then, getContent can be modified to interact with the promise, modifying the response with compileData:

    getContent: function () {
      return url.httpRequest().then(url.compileData);
    }
    

    And, the caller can add its own handler using the Promise's methods:

    url.getContent().then(function (content) {
      // proceed with `content` here
    });
    

    Also, a brief aside... In supporting browsers, you can use fetch() in place of jQuery.ajax(), which already returns a standard Promise, but will first give you a Response object rather than the raw data.

    httpRequest: function () {
      return fetch(document.querySelector("a").href)
        .then(response => response.text())
    }
    
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
0

There are three different ways according to 3 JS standards i.e es5,es6 and es7 but here you have used xhr therefore it is an old standard.

Hence, you should use xhr.onload method of xhr object over here to return the response. Simply do:

xhr.onload = callback; insert this code between xhr.open and xhr.send.

abbaszain
  • 91
  • 5
-1

You need Promises, Promises and more Promises! And you should return one from your function.

function httpRequest() {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onload = (response) => {
            resolve(response); // You should check the response and maybe preprocess it 
                               //   so that not everything is passed further
        }
        xhr.open("GET", document.querySelector("a").href);
        xhr.send("");
    });
}

and then you may use then and catch

httpRequest().then((data) => {
    // Yay! Got response from the server!
}).catch((error) => {
    // Yay! More errors!
});
An0num0us
  • 961
  • 7
  • 15