Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Srikanththyagarajan/8281e24e070edc071eb36bc9cccfea81 to your computer and use it in GitHub Desktop.
Save Srikanththyagarajan/8281e24e070edc071eb36bc9cccfea81 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