当我在调用函数时返回
export function getChampion(id, country) {
$.ajax({
type: "GET",
url: `http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${country}/champion.json`,
dataType: "json",
success: function(data) {
console.log(data);
idToChampion(data, id);
}
});
}
// Return the ChampionId
function idToChampion(data, theId) {
let resultObject = search(theId, data);
console.log(resultObject);
return resultObject.id;
}
function search(key, inputArray) {
inputArray = Object.values(inputArray.data)
for (let i = 0; i < inputArray.length; i++) {
if (inputArray[i].key === key) {
return inputArray[i];
}
}
}函数"getChampion“返回undefined,我不知道为什么以及如何修复它。提前感谢
发布于 2019-12-26 09:49:46
如果你不想让它返回undefined,你可以使用Promise使它成为一个异步函数。
export function getChampion(id, country) {
return new Promise(resolve => {
$.ajax({
type: "GET",
url: `http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${country}/champion.json`,
dataType: "json",
success: function(data) {
resolve(data)
}
});
})
}然后你就可以使用
let data = await getChampion(id, country);
...发布于 2019-12-26 10:04:40
您的getChampion函数没有返回任何值。
假设你想根据他们的id获取冠军数据,你可以尝试这个函数:
async function getChampion({id, lang = "en_US"}) {
const {data} = await $.getJSON(`http://ddragon.leagueoflegends.com/cdn/9.24.2/data/${lang}/champion.json`).promise()
return data[id]
}下面是如何调用它:
(async () => {
console.log(await getChampion("Aatrox"))
//=> { "title": "the Darkin Blade", "blurb": "Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...", ... }
console.log(await getChampion("Ahri"))
//=> { "title": "the Nine-Tailed Fox", "blurb": "Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...", ... }
})()您还可以使用promise接口:
getChampion("Aatrox").then(console.log)
//=> { "title": "the Darkin Blade", "blurb": "Once honored defenders of Shurima against the Void, Aatrox and his brethren would eventually become an even greater threat to Runeterra, and were defeated only by cunning mortal sorcery. But after centuries of imprisonment, Aatrox was the first to find...", ... }
getChampion("Ahri").then(console.log)
//=> { "title": "the Nine-Tailed Fox", "blurb": "Innately connected to the latent power of Runeterra, Ahri is a vastaya who can reshape magic into orbs of raw energy. She revels in toying with her prey by manipulating their emotions before devouring their life essence. Despite her predatory nature...", ... }https://stackoverflow.com/questions/59482947
复制相似问题