I have a wrapper class for fetch promises and I wanted to console out http response statuses.
Currently the switch is inside the get() method. How can I shift this switch case into the error() method and use it as a "thenable"?
Take a look:
class CustomFetch {
get(url) {
return new Promise((resolve, reject) => {
const getOptions = {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type': 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
// body: JSON.stringify(params) // body data type must match "Content-Type" header
};
// DO FETCH
fetch(url, getOptions)
.then(function(res) {
// RESPONSE VALIDATION
switch (res.status) {
case 200:
// code...
console.info('HTTP GET response status:', res.status, 'OK');
break;
case 201:
// code...
console.info('HTTP GET response status:', res.status, 'Created');
break;
case 404:
// code...
throw new Error('HTTP GET response status: 404 Not Found.');
break;
case 500:
// code...
throw new Error('HTTP GET response status: 500 Internal Server Error.');
break;
case 503:
// code...
throw new Error('HTTP GET response status: 503 Service Unavailable.');
break;
default:
// code...
break;
}
return res;
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err));
});
}
error(res) {
// Here, for example..
}
}
const http = new CustomFetch;
async function Run() {
// GET -> AWAIT...
const fetch1 = await http.get('https://jsonplaceholder.typicode.com/users/1')
.then(data => console.log(data))
.then(data => console.log('asycn/await: Resource Get Successful.'))
.then(data => console.log('_'))
.catch(err => console.log(err));
}
// RUN async /await fetch functions in procedural order.
Run();