Skip to content

Instantly share code, notes, and snippets.

@dzsquared
Forked from floriankraft/ajax-with-promise.ts
Created July 24, 2018 15:12
Show Gist options
  • Save dzsquared/fa8894516a91d64798905d0ffe6b0bd7 to your computer and use it in GitHub Desktop.
Save dzsquared/fa8894516a91d64798905d0ffe6b0bd7 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