0

Suppose I have some code like this:-

const Ω = {};
Ω.getJSON = function(url, callback){
      var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function() {
      if (this.status >= 200 && this.status < 400) {
        var data = JSON.parse(this.response);
        callback(data);
      } else {
        console.log(this.status);

      }
    };

    request.onerror = function() {
      throw'An Unknown Error';
    };

    request.send();
    }

I want to define a .fail() function similar to jQuery's $.getJSON one but I have no idea how to do like this.

How can I make a .fail() function for Ω.getJSON?

Answers and comments appreciated.

Pranav
  • 674
  • 1
  • 6
  • 23
  • Using promises would be most practical way to do it but using `fetch()` rather than `XMLHttpRequest` would be more modern approach since it is already promise based – charlietfl Oct 20 '19 at 15:44
  • How can I do that? Could you explain with a example – Pranav Oct 20 '19 at 15:45
  • https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr Note I found this with a simple google search of *"XMLHttpRequest promise"* and there are numerous other results as well – charlietfl Oct 20 '19 at 16:00

0 Answers0