调用Ajax导出函数返回值

时间:2019-12-26 01:03:18

标签: javascript jquery ajax asynchronous

当我用返回的

调用函数时
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”返回未定义,我不明白为什么以及如何解决它。在此先感谢

2 个答案:

答案 0 :(得分:0)

如果您不希望它返回未定义的值,则可以使用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);
...

答案 1 :(得分:0)

您的Pointer.dump()函数不返回任何值。

假设您要根据其ID获取冠军数据,可以尝试以下功能:

getChampion

这里是怎么称呼它:

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]
}

您还可以使用promise界面:

(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...", ... }
})()