Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. const err = 'Bad response from server';
  2.  
  3. // async
  4. const get = async url => {
  5. const res = await fetch(url, {
  6. credentials: 'include',
  7. method: 'GET'
  8. });
  9. if (res.status >= 400) {
  10. throw err;
  11. }
  12. let json;
  13. try {
  14. json = await res.json();
  15. } catch(e) {
  16. if (e.name === 'SyntaxError' && e.message === 'Unexpected end of JSON input') {
  17. json = {};
  18. }
  19. throw e;
  20. }
  21. if (!res.ok) {
  22. throw json.error;
  23. }
  24. return json;
  25. };
  26.  
  27. // promise
  28. const get = url => fetch(url, {
  29. credentials: 'include',
  30. method: 'GET'
  31. }).then(res => {
  32. if (res.status >= 400) {
  33. throw err;
  34. }
  35. return res.json()
  36. .then(json => ({json, res}))
  37. .catch(e => {
  38. if (e.name === 'SyntaxError' && e.message === 'Unexpected end of JSON input') {
  39. return Promise.resolve({json: {}, res});
  40. }
  41. throw e;
  42. });
  43. }).then(({json, res}) => {
  44. if (!res.ok) {
  45. throw json.error;
  46. }
  47. return json;
  48. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement