Returning data resolved by XMLHttpRequest with module pattern function

寵の児 提交于 2019-12-12 05:08:39

问题


I have problem combining javascript callbacks and revealing module pattern. What I'm trying to do is to return the HTTP response text with the carsData.getCars() function method.

Basically what I want to do is:

  1. return the data from xhr.onreadystatechange function to the private getData function
  2. return the data from getData function to the public getCars function ( or call the getCars function returning a value)

I got it to work with the synchronous AJAX mode, but I'm aware it's not the best practice in javascript development.

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

P.S. I use XMLHttpRequest in Vanilla JS instead of other frameworks for learning purposes.

'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]}
            })
        }

    }
})();

回答1:


No. You cannot do it this way. I figured out that is why you typically see results sent to a DOM object. Because they are there waiting for the answer. Your return statement, as counter-intuitive as it seems (assuming you are coming from non-prototype languages), will have already run. It seems like it wouldn't but it has because of the async nature you are aware of. You have to use Promises or you have to have your callback doing something with the data that is "waiting" for the callback data like you did with successdata.



来源:https://stackoverflow.com/questions/37615084/returning-data-resolved-by-xmlhttprequest-with-module-pattern-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!