Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

    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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading