race.js 824 B

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