0

I am trying to make an object with a get function that takes in a URL, creates a GET request, then returns the responseText. But, with my current code, whenever I try to log it I get undefined.

var HttpRequest = function() {
  this.get = function(url, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
      if(httpRequest.readyState == 4 && httpRequest.status == 200) {
        callback = httpRequest.responseText;
      }
    };
    httpRequest.open("GET", url, true);
    httpRequest.send(null);
    return callback;
  };
};

var request = new HttpRequest();

var response = request.get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD");
console.log(response);

EDIT: After this question got marked as a duplicate, I look at the question that I 'duplicated' and I fixed my problem, but I don't understand why return won't work. I have updated my code to something that SHOULD work, but doesn't. A callback is a function that is called after something is completed, but why won't return work in place of it?

Updated code: var HttpRequest = function() { this.get = function(url) {

    var httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = function() {
      if(httpRequest.readyState == 4 && httpRequest.status == 200) {
        return httpRequest.responseText;
      }
    };
    httpRequest.open("GET", url, true);
    httpRequest.send(null);
  };
};

var request = new HttpRequest();

var response = request.get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD", "blank");
console.log(response);
Jordan Baron
  • 3,752
  • 4
  • 15
  • 26
  • 5
    It seems that `get()` returns its own second parameter called `callback`, which is undefined in your call. – DontVoteMeDown May 10 '18 at 18:34
  • You must understand the order in which each line of code is called. Open up the developer tools and set breakpoints, you will see that your `console.log` line is called way before the AJAX call returns. You are trying to log the value but the AJAX call has not finished yet. – Pop-A-Stash May 10 '18 at 19:19

0 Answers0