Skip to content

Instantly share code, notes, and snippets.

@koistya
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save koistya/e399a3d4aa3700cbfc89 to your computer and use it in GitHub Desktop.

Select an option

Save koistya/e399a3d4aa3700cbfc89 to your computer and use it in GitHub Desktop.
var HttpClient = require('./core/HttpClient');
var http = new HttpClient();

http.get('/api/values').then((res) => {
  // Handle the response
}, (err) => {
  // Handle the error
});
var { Promise } = require('es6-promise');
export class HttpClient {
get(url) {
// Return a new promise
return new Promise((resolve, reject) => {
// Do the usual XHR stuff
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => {
// This is called even on 404 etc.
// so check the status
if (request.status >= 200 && request.status < 400) {
// Resolve the promise with the response JSON
resolve(JSON.parse(request.responseText));
} else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(request.statusText));
}
};
// Handle network errors
request.onerror = () => {
reject(Error('Network error'));
};
// Make the request
request.send();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment