我想用英雄联盟API做一些练习编码。为此,您首先需要两条信息:补丁版本(例如" 7.12.1")和冠军数据(JSON)。
我遇到的问题是,即使使用我的嵌套承诺,GetData()也不会等待GetPatch()解析。
var URL = "https://ddragon.leagueoflegends.com/"
var patch, data
var GetPatch = new Promise(function(resolve) {
$.getJSON(URL + "api/versions.json", f = x => {
patch = x[0]
console.log("patch version: " + patch)
resolve()
})
})
var GetData = new Promise(function(resolve) {
$.getJSON(URL + "cdn/" + patch + "/data/en_US/champion.json", g = x => {
data = x.data
console.log(data)
resolve()
})
})
GetPatch.then(function() {
GetData.then(function() {
RunApp()
})
})
function RunApp() {
console.log("everything is working")
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
&#13;
答案 0 :(得分:2)
首先,像$ .AJAX这样的jQuery AJAX函数已经返回了一个promise
其次,您设置承诺的方式是,您立即运行$ .getJSON
您的代码可能类似于 - 请注意缺少var patch, data
var URL = "https://ddragon.leagueoflegends.com/"
var GetPatch = function() {
return $.getJSON(URL + "api/versions.json").then(x => x[0]);
})
var GetData = function (patch) {
return $.getJSON(URL + "cdn/" + patch + "/data/en_US/champion.json").then(x => ({patch: patch, data: x.data}));
})
GetPatch()
.then(GetData)
.then(RunApp);
function RunApp({patch, data}) {
// here you can access patch and data if you need to
console.log("everything is working")
}
如果您只需data
RunApp
return $.getJSON(URL + "cdn/" + patch + "/data/en_US/champion.json").then(x => x.data);
...
function RunApp(data) {
// here you can access data
console.log("everything is working")
}
另一种选择 - 可能&#34; neater&#34;
var URL = "https://ddragon.leagueoflegends.com/"
var GetPatch = function() {
return $.getJSON(URL + "api/versions.json");
})
var GetData = function (patch) {
// note the patch[0] below
return $.getJSON(URL + "cdn/" + patch[0] + "/data/en_US/champion.json");
})
GetPatch()
.then(GetData)
.then(RunApp);
function RunApp(result) {
// result.data is what x.data was in your code
console.log("everything is working")
}