-
-
Save phothinmg/50840617a77f2b3c7df5bc6ebb604595 to your computer and use it in GitHub Desktop.
Pure JS HTTPRequest Implementation using Promise
This file contains hidden or 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
| function makeRequest(method, url, data){ | |
| return new Promise( | |
| function(resolve, reject) | |
| { | |
| var http = new XMLHttpRequest(); | |
| http.open(method, url); | |
| http.onload= function(){ | |
| if(this.status >= 200 && this.status < 300) | |
| { | |
| var response = http.response; | |
| try | |
| { | |
| response = JSON.parse(response); | |
| resolve(response); | |
| } | |
| catch (error) | |
| { | |
| reject({ | |
| status: this.status, | |
| statusText: error | |
| }); | |
| } | |
| } | |
| else | |
| { | |
| reject({ | |
| status: this.status, | |
| statusText: http.statusText | |
| }); | |
| } | |
| }; | |
| http.onerror = function(){ | |
| reject({ | |
| status: this.status, | |
| statusText: http.statusText | |
| }); | |
| }; | |
| if(method === 'POST') | |
| { | |
| data = data || {}; | |
| http.send(JSON.stringify(data)); | |
| } | |
| else http.send(); | |
| } | |
| ); | |
| } | |
| function getRequest(url){ | |
| return makeRequest('GET', url); | |
| } | |
| function postRequest(url, data){ | |
| return makeRequest('POST', url, data); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment