Last active
February 11, 2020 06:24
-
-
Save manar007/74f5ea6fa1614b4e8e5d to your computer and use it in GitHub Desktop.
Promises with vanilla js, helper http function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
worked great. thanks!