Skip to content

Instantly share code, notes, and snippets.

@floriankraft
Created January 15, 2017 11:33
Show Gist options
  • Save floriankraft/f84dbf3cf5c0ece164cfdb4246eab5d4 to your computer and use it in GitHub Desktop.
Save floriankraft/f84dbf3cf5c0ece164cfdb4246eab5d4 to your computer and use it in GitHub Desktop.
HTTP Request with Promises in Typescript
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