Return Data Allowed by XMLHttpRequest Using a Module Template Function

I have a problem with javascript callbacks bundling and module pattern detection. I am trying to return the HTTP response text using a function method carsData.getCars()

.

Basically what I want to do:

  • returns data from function xhr.onreadystatechange

    to private getData

    function
  • return data from a function getData

    to a public function getCars

    (or call a function getCars

    that returns a value)

I got it to work with synchronous AJAX mode, but I know this is not javascript best practice.

I tried to get it to work with callbacks but failed miserably. Is it possible to do this in javascript?

PS I'm using XMLHttpRequest

Vanilla JS instead of other learning frameworks.

'use strict';
var carsData = (function() {
    var carsElement = document.getElementById('carsListing'),
        successHandler = function(data) {
            carsElement.innerHTML = data.data;
            //return data;
        },
        dataWrapper = "",
        getData = function(callback) {
            var url = 'data/cars.json',
                xhr = new XMLHttpRequest();    

            xhr.onreadystatechange = function() {
                var status;
                var data;

                if (xhr.readyState == 4) { // `DONE`
                    status = xhr.status;
                    if (status == 200) {
                        data = JSON.parse(xhr.responseText);
                        successHandler && successHandler(data);
                        callback(data);
                        return data;
                    }
                }
            };
            xhr.open('get', url, false); // synchronous js
            xhr.send();
            return xhr.onreadystatechange();
            //return 'xx';
        }

    return {
        getCars: function() {
            return getData(function(data){
              console.log(data); // Object {data: Array[5]}
            })
        }

    }
})();

      

0


source to share


1 answer


Not. You cannot do it this way. I realized that you usually see results sent to the DOM object. Because they are there waiting for an answer. Your return statement, as intuitive as it sounds (assuming you are coming from non-prototypal languages), will already be running. It looks like it is not, but this is due to the asynchronous nature that you are aware of. You must use Promises, or you need your callback to do something with data that "expects" the callback data, as you did with successdata

.



0


source







All Articles