0

I'm trying to get data from an API, but I can't get outside result from the .then.

function getChampionMasteryData(championId, summonerName) {  
    var championMasteryData;
    var summonerId = process.env.SUMMONER_ID;

    axios.get(`https://euw1.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/${summonerId}/by-champion/${championId}?api_key=${process.env.API_KEY}`, {responseType: 'json'})
        .then(result => {championMasteryData = result.data})
        .catch(e => console.log(e));

    console.log(championMasteryData);
    return championMasteryData;
}

output:

undefined
Deku
  • 11
  • 2
  • You can't access `championMasteryData` inside of `.then` as it is not in it's closure. A fix would be to use `async/await`, load the response of the API in a variable and then change the value of `championMasteryData` – Yash Verma Feb 25 '22 at 21:51
  • I tried that, and the difference is that I take a Promise pending and i don't find a way to resolve it and take inside data. – Deku Feb 25 '22 at 21:57
  • use async await function – Wasif Ali Feb 25 '22 at 21:58
  • let championmasterydata = await axioscall; console.log(masteryData) – Wasif Ali Feb 25 '22 at 21:59
  • [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Đinh Carabus Feb 25 '22 at 22:18

0 Answers0