Created
January 15, 2017 11:33
-
-
Save floriankraft/f84dbf3cf5c0ece164cfdb4246eab5d4 to your computer and use it in GitHub Desktop.
HTTP Request with Promises in Typescript
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
getRequest(url: string): Promise<any> { | |
return new Promise<any>( | |
function (resolve, reject) { | |
const request = new XMLHttpRequest(); | |
request.onload = function () { | |
if (this.status === 200) { | |
resolve(this.response); | |
} else { | |
reject(new Error(this.statusText)); | |
} | |
}; | |
request.onerror = function () { | |
reject(new Error('XMLHttpRequest Error: ' + this.statusText)); | |
}; | |
request.open('GET', url); | |
request.send(); | |
}); | |
getRequest('http://some.url') | |
.then(response => { | |
console.log(response); | |
}) | |
.catch(error => { | |
console.log(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment