I'm doing a function that makes a synchronized ajax call to a server. The problem is that when I call the function, the main doesn't wait for the data propagation.
I explain myself better:
I need to return some data from a function:
var firstdate = getLastPaycheck();
this function is:
function getLastPaycheck() {
let returnValue = sessionStorage.getItem('last_paycheck');
if (returnValue == "" || returnValue == null) {
const message = { "cookie": getCookie("userCookie") };
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', complete, false);
xhr.open("POST", '/getLastPaycheck', false);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(message));
function complete(e) {//Call a function when the state changes.
const response = JSON.parse(xhr.responseText);
console.log("Value taken from the server");
returnValue = moment(response.value[0].last_paycheck).format(getDateFormat("iso"));
return returnValue;
console.log("Returned value");
} // if readyStatus = 200;
} else {
console.log("Value taken from the session");
return returnValue;
}
}
the problem is that the value of "firstdate" is always undefined when the data is taken from the server.
Could someone explain me how to do that?
Thank you. I apreciate it.