Skip to content

Instantly share code, notes, and snippets.

@manar007
Last active February 11, 2020 06:24
Show Gist options
  • Save manar007/74f5ea6fa1614b4e8e5d to your computer and use it in GitHub Desktop.
Save manar007/74f5ea6fa1614b4e8e5d to your computer and use it in GitHub Desktop.
Promises with vanilla js, helper http function
// Support: http://caniuse.com/promises
function Http () {
/**
* Helper for http calls
* @param method
* @param url
* @param data
* @returns {Promise}
*/
function makeRequest(method,url,data) {
var data = data || '';
// Return a new promise.
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open(method, url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Something went wrong ... "));
};
req.send(data);
});
}
this.makeRequest = makeRequest;
}
//// usage example
var http = new Http();
http.makeRequest('GET', 'data.json').then(
function (response) {
console.log("Success!", response);
}, function (error) {
console.error("Failed!", error);
});
@jackson-sandland
Copy link

worked great. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment