-
-
Save phothinmg/18d3362403d1506c425141f696b56505 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