How do I promisify native XHR?

I want to use (native) promises in my frontend app to perform XHR request but without all the tomfoolery of a massive framework.

I want my xhr to return a promise but this doesn’t work (giving me: Uncaught TypeError: Promise resolver undefined is not a function)

function makeXHRRequest (method, url, done) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.onload = function() { return new Promise().resolve(); };
  xhr.onerror = function() { return new Promise().reject(); };
  xhr.send();
}

makeXHRRequest('GET', 'http://example.com')
.then(function (datums) {
  console.log(datums);
});

6 Answers
6

Leave a Comment