nbl
Version:
30 lines (26 loc) • 1.29 kB
text/typescript
function httpreq(type:string,baseURL:string) {
return new Promise( (resolve, reject) => {
// The promise is now in the 'Pending' state
const xhr = new XMLHttpRequest();
xhr.open(type, baseURL);
xhr.send()
xhr.onreadystatechange = () => {
if (xhr.readyState < 4) {
// The XHR request hasn't completed yet, so I'm just going to return here.
return;
}
if (xhr.status !== 200) {
// The Status code of the request is NOT 200, so it must have failed in some way. Reject the promise
reject(xhr.response);
// After calling reject(), the Promise enters 'rejected' state.
}
if (xhr.readyState === 4) {
// The readyState of the request is '4', which means its done.
// Parse the response into JSON format and resolve the promise
resolve(JSON.parse(xhr.response));
// After calling resolve(), the Promise enters 'resolved' or 'fulfilled' state.
}
}
});
}
export default httpreq;