-1

I'm trying to get data from an API request but I don't know why await does not wait to get data to return value. Anyone can help me?

async function getChampionMasteryData(championId, summonerName) {  
    try {
        var summonerId = process.env.SUMMONER_ID;
        
        let championMasteryData = await axios(`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'});

        return championMasteryData.data;
    } catch (e) {
        console.log(e);
    }
}

Output:

Promise { <pending> }
Deku
  • 11
  • 2
  • What happens? Do you get an error message? What's the value of `championMasteryData`? – jabaa Feb 26 '22 at 00:40
  • the return is a promise pending. – Deku Feb 26 '22 at 00:41
  • How did you log the returned value? – jabaa Feb 26 '22 at 00:44
  • Because async functions _always_ return a promise, and so whatever function is calling `getChampionMasteryData` should be async too. In fact I would just return the data from the function without it being async, and let the function that's calling it deal with the `try/catch`. – Andy Feb 26 '22 at 00:46

1 Answers1

1

It's quite likely that you are not awaiting for the getChampionMasteryData function. You should call it like await getChampionMasteryData(championId, summonerName) instead of calling it directly.

If you want to call it from a non-async function, you can use then to wait until it resolves like below,

getChampionMasteryData(championId, summonerName).then((data) => {
    console.log(data);
});
archon
  • 183
  • 8
  • I've done this, but still returning me a promise pending: " const championMasteryData = lolapi.getChampionMasteryData(championId, 'manufm').then( res => console.log(res.data) ); console.log(championMasteryData);" – Deku Feb 26 '22 at 00:54
  • Can you share the code that you're calling this function from? – archon Feb 26 '22 at 00:55
  • https://github.com/gitatmanu/Champion-Mastery-Display-for-OBS – Deku Feb 26 '22 at 00:57
  • The problem is in `http.createServer(function (req, res)`, it needs to be like `http.createServer(async function (req, res) { ...` and after doing this, you'll be able to await before ending the response. You also have to change the `lolapi.getChampionMasteryData ...).then` part to `await lolapi.getChampionMasteryData()`. To clarify why you can't do it the other way, your callback function is not `async`, and inside your callback function you're trying to `await`. It either has to be `async` or you should put res.end and res.writeHead inside the `then` callback. – archon Feb 26 '22 at 01:01
  • Lol, you're welcome. Edited the comment so you can have a better idea of how it works in general. – archon Feb 26 '22 at 01:05
  • I appreciate your help to teach me, thank you and have a good day! – Deku Feb 26 '22 at 01:06