gpt4 book ai didi

javascript - 嵌套 Promise 不起作用(jquery + 英雄联盟 API)

转载 作者:行者123 更新时间:2023-12-01 03:30:41 24 4
gpt4 key购买 nike

我想使用英雄联盟 API 进行一些编码练习。为此,您首先需要两条信息:补丁版本(例如“7.12.1”)和冠军数据(JSON)。

我遇到的问题是,即使有嵌套的 promise ,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>

最佳答案

首先,像 $.AJAX 这样的 jQuery AJAX 函数已经返回了一个 promise

其次,您设置 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")
}

如果您只需要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")
}

另一种选择 - 可能“更整洁”

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")
}

关于javascript - 嵌套 Promise 不起作用(jquery + 英雄联盟 API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44556998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com