This is a very simple callback function but I still can’t wrap my mind around it. Can someone try to explain it to me?
const getToDos = (one) => {
const req = new XMLHttpRequest();
req.addEventListener(`readystatechange`, () => {
if (req.readyState === 4 && req.status === 200) {
one(undefined, req.responseText);
}
else if (req.readyState === 4) {
one(`couldnt fetch data`, undefined);
}
});
req.open(`GET`, `https://jsonplaceholder.typicode.com/todos/`);
req.send();
};
getToDos((err, data) => {
if (err) {
console.log(err);
}
else {
console.log(data);
}
});
Also, can someone tell me what the difference is between XMLHttpRequest
and the GET
method? Are XMLHttpRequest
s used in the front end and GET
methods used in the back end?
//Defining getToDos function, it takes one argument, which is another function
const getToDos = (one) => {
//Create a request
const req = new XMLHttpRequest();
//Add an event listener on the status of the request and gives code to execute when it happens
req.addEventListener(`readystatechange`, () => {
//if request is completed (4) and its status is good (200)
if (req.readyState === 4 && req.status === 200) {
//Call the callback function give undefined as error and req.responseText as data
one(undefined, req.responseText);
//if request is completed (4) and its status is good (!= 200)
} else if (req.readyState === 4) {
//Call the callback function give `couldnt fetch data` as error and undefined as data
one(`couldnt fetch data`, undefined);
}
});
//prepare request and give endpoint
req.open(`GET`, `https://jsonplaceholder.typicode.com/todos/`);
//send request
req.send();
};
//execute getToDos function and give a function as parameter
getToDos((err, data) => {
//if err is not undefined
if (err) {
//log error
console.log(err);
} else {
//log data
console.log(data);
}
});
This kind of code is old. Instead you should :
let data = await fetch(`https://jsonplaceholder.typicode.com/todos/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
})
if(data.status == 200){
let parsed = await data.json()
console.log(parsed)
} else {
console.log(data)
}
––––– Edit: Added example for the OP
const aFunction = (callback) => {
const aRandomBoolean = Math.random() < 0.5
if(aRandomBoolean){
console.log('Boolean is true !')
callback('first parameter', 'second parameter')
} else {
console.log('Boolean is false !')
callback('parameter 1', 'parameter 2')
}
}
aFunction((paramA, paramB)=>{
console.log(paramA, paramB)
})