0

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.

1
  • Your connection may be synchronous but you're still relying on events, which are not. Additionally, your return statements inside the callback function would not trigger a return from the outer function. Commented Apr 30, 2018 at 12:48

2 Answers 2

2

You may also do it using callbacks:

    function getLastPaycheck(callback) {
        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"));
                    callback(returnValue);
                console.log("Returned value");
                } // if readyStatus = 200;

        } else {
            console.log("Value taken from the session");
            callback(returnValue);
        }
    }

    getLastPaycheck(function(data) {
      // data is accessible here
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you but seems to don't work :/ I did getLastPaycheck(function (data) { startdate.value = data; }); but it seems to don't work. This is I made the function: function getLastPaycheck(callback) { let returnValue = sessionStorage.getItem('last_paycheck'); ...
Well, it could be because it's not getting inside the if statement. Inside else, also do callback(returnValue). Check the edit.
Allright! It works, I forgot to change "return" with "callback"! Thank you so much, I have a due of a brew!
1

You can use ES6 async-await and then simply call

var firstdate = await getLastPaycheck();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.