Search code examples
javascriptjquerygetjson

How to make getJSON code cleaner looking?


Is there a way to rewrite the following code so that it looks cleaner. Maybe using await? I really don't like the idea of having nested functions, but I need to wait till I get both .json files loaded before my app can start...

Any idea how to clean this up?

 $.getJSON('myFile1.json', function(data) {
      var myFile = data;
      $.getJSON('myFile2.json', function(data) {
          var myFile2 = data;
          // Do stuff. 
          return 0;
      });
      return 0;
});

Thanks!


Solution

  • You could use $.when()

    var getJson1 = $.getJSON('myFile1.json');
    var getJson2 = $.getJSON('myFile2.json');
    $.when(getJson1, getJson2).done(function(data1, data2){
        ...
    });