DEV Community

AlexMcD-git
AlexMcD-git

Posted on

Recursive Fetching In Javascript

For my latest project, I am working on finding degrees of separation between a given player, and the top ranked group, known as "Challenger"(which consists of the top 200) in the game League of Legends. All of this is made possible by the RiotAPI.

The process I had in mind was to look up other players from the 10 most recent games, find the highest ranked player, and repeat the process with said player if they are not a "Challenger" rank. The basic structure of the process would be:

function findChallenger(playerID){
    //lookup recent games with playerID
    //lookup players from those games
    //find the rank information on those players
    //sort the players by rank
    if (highestRankedPlayer.tier!== "CHALLENGER"){
        findChallenger(highestRankedPlayer.id)
    }
}
Enter fullscreen mode Exit fullscreen mode

In order to implement this with data from the API, fetch requests need to be made. Not only that, but the data for each fetch is reliant on the data from the previous fetch. In order for this to work we need to made the 2nd fetch after the promise of the first is resolved, like so:
(using "data1.url" as an example of how the data of the first fetch is necessary towards making the 2nd)

fetch(url1)
.then(response1=>response1.json())
.then(data1=>{
    fetch(data1.url)
    .then(response2=>response2.json()
    .then(data2=>/*process data2*/)
    }
)
Enter fullscreen mode Exit fullscreen mode

In this manner I "nested" fetch requests in order to reach all the API endpoints necessary for the functionality of my project on github here, and the specifics of making these calls are available on this particular file. The particular point of recursion is where, within "findChallenger(){}" (after the best player from your 10 most recent games is found)

if (bestPlayer.tier ==="CHALLENGER"){
    return
}
else{
    summonerLookup(bestPlayer.summonerName)
}
Enter fullscreen mode Exit fullscreen mode

I would recommend anyone looking to try out an API requiring authentication give the RiotAPI a go (being familiar with League of Legends, Valorant, or Legends of Runeterra is also helpful) due to the generous rate limits, intuitive end points, and ease of applying for an increase.

Top comments (0)