12345678910111213141516171819202122232425 |
- const myfetch = (method, url) => {
- return new Promise((resolve, reject) => {
- const errorObj = xhr => {
- return {
- status: xhr.status,
- statusText: xhr.statusText
- }
- }
- const xhr = new XMLHttpRequest();
- xhr.open(method, url);
- xhr.onload = () => {
- if (xhr.status !== 200) {
- reject(errorObj(xhr));
- } else {
- resolve(JSON.parse(xhr.response));
- }
- };
- xhr.onerror = () => reject(errorObj(xhr));
- xhr.send();
- });
- }
- myfetch('GET', 'https://swapi.dev/api/people/1/')
- .then(luke => console.log(luke))
- .catch(error => console.error('There was an error!', error.statusText));
|