如何使getJSON代码更清晰?

时间:2018-01-03 22:45:52

标签: javascript jquery getjson

有没有办法重写以下代码,使其看起来更干净。也许使用await? 我真的不喜欢嵌套函数的想法,但我需要等到我的应用程序启动之前加载两个.json文件...

知道如何清理它吗?

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

谢谢!

4 个答案:

答案 0 :(得分:1)

你想要承诺,我的男人。

Native promise

Jquery promise

答案 1 :(得分:0)

您可以使用$.when()

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

答案 2 :(得分:0)

getJSON的返回值放在数组中。将其传递给Promise.all。当它解析时(两个getJSON promises都已解决),它将有一个包含所有数据的数组。



var urls = ["https://api.domainsdb.info/search?query=microsoft", "https://api.domainsdb.info/search?query=google"];

Promise.all([
  $.getJSON(urls[0]),
  $.getJSON(urls[1])
]).then((data) => console.log({
  "Total Microsoft domains": data[0].total,
  "Total Google domains": data[1].total,
  "Grand total": data[0].total + data[1].total
}));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

getJSON返回一个promise https://api.jquery.com/promise/。所以这种事情有效:

var firstPromise = $.getJSON('myFile1.json');
var secondPromise = $.getJSON('myFile2.json');

$.when(firstPromise, secondPromise).done(function(firstData, secondData) {
  // do something
});
相关问题