-
-
Save Srikanththyagarajan/8281e24e070edc071eb36bc9cccfea81 to your computer and use it in GitHub Desktop.
HTTP Request with Promises in Typescript
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
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