Home > OS >  How do I make an express route to a string that is only loaded after a promise from an API call?
How do I make an express route to a string that is only loaded after a promise from an API call?

Time:02-27

    app.get(`/${sumName}`, async (req, res) => {
        const link = `https://na1.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5?api_key=${RiotKey}`
        const response = await fetch(link);
        let data = await response.json();
        sumName = data.entries[0].summonerName
        res.send("Works")
    })

The issue I'm having is that sumName is not defined (I believe this is because sumName is only defined within the scope of the function, and doesn't reach the function argument)

However, if I try to pass sumName or anything from data.entries from outside of the function, it will return an object Promise instead of the data. Is there a way to pass this data from inside of the function? Creating a new async function doesn't work because it will still return an object Promise when app.get is called.

CodePudding user response:

You don't need to call app.get to define the route immediately - feel free to do so after the API finishes.

fetch(`https://na1.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5?api_key=${RiotKey}`)
    .then(res => res.json())
    .then((data) => {
        const sumName = data.entries[0].summonerName;
        app.get(`/${sumName}`, (req, res) => {
            res.send("Works");
        });
    })
    // .catch(handleErrors); // don't forget this
  • Related