Search code examples
javascriptjsonasynchronousmodular

Load JSON file modular view javascript approach


I am trying to implement a modular view approach for calling a json file in my javascript code, but not able to rectify the issue. The code where I am calling json file is a separate js file which is as follows:

var fileConfigModule = (function () {

  var arData = {};

  function init() {
    loadJSON(function (json) {
      arData = json
    });
    return arData 
  }
  // Let's hide this function

  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', './data.json', true);
    xobj.onreadystatechange = function () {
      if (xobj.readyState == 4 && xobj.status == "200") {
        arVals= callback(JSON.parse(xobj.responseText));
      }
    };
    xobj.send(null);
  }

  return {
    loadJSON: loadJSON,
    init: init
  }
})();

I want to use this module in my main file to get the json loaded from file something like this aysnc. This uses a call back function.

var arData = fileConfigModule.init(); 

Please if someone can help, what I am doing wrong here. Many thanks


Solution

  • You're calling an async function but expecting return value as sync function.

    Update your code as below,

    var fileConfigModule = (function () {
    
      function init(callback) {
        loadJSON(function (json) {
          callback(json);
        });
      }
      // Let's hide this function
    
      function loadJSON(callback) {
        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', './data.json', true);
        xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            callback(JSON.parse(xobj.responseText));
          }
        };
        xobj.send();
      }
    
      return {
        loadJSON: loadJSON,
        init: init
      }
    })();
    

    And call as below,

    var arData = null;
    fileConfigModule.init(function(data){
      arData = data;
    }); 
    

    I don't know why you're trying to hide loadJSON function. But I think you should directly use the loadJSON function, instead of calling the init function.

    Calling loadJSON,

    var arData = null;
    fileConfigModule.loadJSON(function(data){
      arData = data;
    });