Can someone explain line by line how the logic here is working exactly, and how it is different than the way freecodecamp teaches doing it here
the below code snippet is from the free online course found here
function getData(method, url){
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function(){
if(this.status >= 200 && this.status < 300){
console.log(xhr.response)
resolve(xhr.response);
}else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function(){
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
It’s the same, except the functionality has been wrapped up into a function that returns a Promise.
So given a method (GET, POST, etc), and a URL, make an HTTP request using XMLHttpRequest, and deal with a successful response or a failure. note afaics it can’t really work for any method that has a body (POST for example) as nowhere in the function is there anywhere to put the body.
If the response status is 200-300, then resolve the promise (eg unwrap the value that comes back). If it isn’t, reject the promise (ie it has failed). If there is an error, also reject the promise.
Returning a Promise allows the function to work the same way as most modern APIs (rather than the highly imperative way XMLHttpRequest works normally). It has the same end result, but it’s normally easier to work with, for example:
getData('GET', 'https://some.api.com')
.then(response => JSON.parse(response))
.then(data => console.log(data))
.catch(err => console.log(err));
In be easily used with async/await syntax as well, as async/await is just alternative syntax for Promises.
It’s basically a copy of how fetch
is normally implemented.
1 Like