I want to create my own fetch function to understand better XMLHttpRequest, Promises and Async/Await.
It doesn't seem like it's returning a promise as I get errors with then()
const fakeFetch = url => {
const xhr = () => new Promise((resolve, reject) => {
try {
const x = new XMLHttpRequest();
x.onreadystatechange = function() {
const { readyState, status } = this;
if (readyState === 4 && status === 200) {
resolve(x.responseText);
}
}
x.open('get', url);
x.send();
} catch(e) {
reject(e);
}
})
const _fetch = () => new Promise(async (resolve, reject) => {
try {
const response = await xhr();
if (response !== undefined) resolve(response);
} catch(e) {
reject(e);
}
})
_fetch();
}
fakeFetch('https://api.github.com/users')
.then(data => data.json())
.then(data => console.log(data));