Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const err = 'Bad response from server';
- // async
- const get = async url => {
- const res = await fetch(url, {
- credentials: 'include',
- method: 'GET'
- });
- if (res.status >= 400) {
- throw err;
- }
- let json;
- try {
- json = await res.json();
- } catch(e) {
- if (e.name === 'SyntaxError' && e.message === 'Unexpected end of JSON input') {
- json = {};
- }
- throw e;
- }
- if (!res.ok) {
- throw json.error;
- }
- return json;
- };
- // promise
- const get = url => fetch(url, {
- credentials: 'include',
- method: 'GET'
- }).then(res => {
- if (res.status >= 400) {
- throw err;
- }
- return res.json()
- .then(json => ({json, res}))
- .catch(e => {
- if (e.name === 'SyntaxError' && e.message === 'Unexpected end of JSON input') {
- return Promise.resolve({json: {}, res});
- }
- throw e;
- });
- }).then(({json, res}) => {
- if (!res.ok) {
- throw json.error;
- }
- return json;
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement