myfetch.js 631 B

12345678910111213141516171819202122232425
  1. const myfetch = (method, url) => {
  2. return new Promise((resolve, reject) => {
  3. const errorObj = xhr => {
  4. return {
  5. status: xhr.status,
  6. statusText: xhr.statusText
  7. }
  8. }
  9. const xhr = new XMLHttpRequest();
  10. xhr.open(method, url);
  11. xhr.onload = () => {
  12. if (xhr.status !== 200) {
  13. reject(errorObj(xhr));
  14. } else {
  15. resolve(JSON.parse(xhr.response));
  16. }
  17. };
  18. xhr.onerror = () => reject(errorObj(xhr));
  19. xhr.send();
  20. });
  21. }
  22. myfetch('GET', 'https://swapi.dev/api/people/1/')
  23. .then(luke => console.log(luke))
  24. .catch(error => console.error('There was an error!', error.statusText));