如何使getJSON代码更清晰? [重复]

问题描述 投票:0回答:4

这个问题在这里已有答案:

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

知道如何清理它吗?

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

谢谢!

javascript jquery getjson
4个回答
0
投票

你可以使用$.when()

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

1
投票

你想要承诺,我的男人。

Native promise

Jquery promise


0
投票

getJSON的返回值放在数组中。把它传递给Promise.all。当它解析时(这将是两个getJSON承诺已经解决的时候),它将有一个包含所有数据的数组。

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>

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
});
© www.soinside.com 2019 - 2024. All rights reserved.