这个问题在这里已有答案:
有没有办法重写以下代码,使其看起来更干净。也许使用await
?我真的不喜欢嵌套函数的想法,但我需要等到我的应用程序启动之前加载两个.json文件...
知道如何清理它吗?
$.getJSON('myFile1.json', function(data) {
var myFile = data;
$.getJSON('myFile2.json', function(data) {
var myFile2 = data;
// Do stuff.
return 0;
});
return 0;
});
谢谢!
你可以使用$.when()
var getJson1 = $.getJSON('myFile1.json');
var getJson2 = $.getJSON('myFile2.json');
$.when(getJson1, getJson2).done(function(data1, data2){
...
});
将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>
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
});