0

I want to return an object from inside getMine function in Javascript but when I try to print out the object, I get undefined. How would you return the obj in the following function?

            function getMine() {
                var httpRequest = new XMLHttpRequest();
                httpRequest.onreadystatechange = function() {
                    if (httpRequest.readyState === 4) { // request is done
                        if (httpRequest.status === 200) { // successfully
                            var obj = JSON.parse(httpRequest.responseText)
                            return obj;
                        }
                    }
                };
                httpRequest.open('GET', "/getTest");
                httpRequest.send();
            }
            var rs = getMine();
            console.log("2", rs);
  • use httpRequest.open('GET', "/getTest", false); to force a return wait. – dandavis Aug 25 '14 at 02:51
  • Not supposed to use `false` option... it takes forever for my app –  Aug 25 '14 at 02:59
  • 1
    it takes the same amount of time, it's just that if you want to bring the data to the action instead of the action to the data, everything else must wait. the answer is not to log() at the bottom, but in the callback. – dandavis Aug 25 '14 at 03:00

1 Answers1

0

Because getMine is making an ajax call, it is by its nature asynchronous. When you attempt to log the value of rs immediately after making a call to getMine(), the ajax call hasn't yet finished. Add your console.log call to the onreadystatechange callback instead:

httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var obj = JSON.parse(httpRequest.responseText);
            console.log('responseText: ', responseText);
            return obj;
        }
    }
};

If you need to be able to do something with the return value, then you may want to look into using promises to handle the asynchronous resolution of an ajax call.

kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • Then how would you enforce to use the returned value waiting for this to finish? –  Aug 25 '14 at 02:29
  • I'd either use a framework that facilitated this, such as jQuery, or I'd use promises, as I alluded to with the promises link. – kinakuta Aug 25 '14 at 03:14