From d8f20b7971bf4c4ab8246dbf2b1bc8e88c055ade Mon Sep 17 00:00:00 2001 From: Alois Klink Date: Mon, 4 Oct 2021 09:26:54 +0100 Subject: [PATCH] Download leaderboard scores in parallel Hiya, first of all, I'm loving this project, one of the coolest things I've seen! I noticed that loading the leaderboard using the plugin is really slow on my computer (although that might just be my slow internet speeds talking). This is because we are sequentially downloading the address and score for each player, instead of downloading them all at the same time. This will get worse as more and more people join the colossus. This PR uses [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) to download all scores at the same time, greatly speeding it up. (By the way, you can enable the ESLint rule [`no-await-in-loop`](https://eslint.org/docs/rules/no-await-in-loop) to check for places where you have an `await` in a loop, when you might be able to use `Promise.all()`) --- plugins/hooks/use-leaderboard.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/plugins/hooks/use-leaderboard.ts b/plugins/hooks/use-leaderboard.ts index db6b34a..6f228e5 100644 --- a/plugins/hooks/use-leaderboard.ts +++ b/plugins/hooks/use-leaderboard.ts @@ -34,14 +34,14 @@ export const useLeaderboard = () => { }) console.log('lb', officialLeaderboard.entries) return colossus.playerCounter().then(async count => { - const lb = [] - for(let i = 0; i < Number(count); i++) { + // load all scores in parallel using promises + const lb = await Promise.all([...Array(Number(count))].map(async (_unused, i) => { const address = await colossus.players(i); const playerScore = await colossus.contributions(address); - const score = Number(playerScore) + const score = Number(playerScore); console.log(`addy ${address} score ${score}`); - lb.push({ address, score, rank: 0 }) - } + return { address, score, rank: 0 }; + })); const leaderboardRanked = lb.sort((a, b) => b.score - a.score ).map((entry, index) => { return {...entry, rank: index + 1 } }) @@ -61,4 +61,4 @@ export const useLeaderboard = () => { loading, error } -} \ No newline at end of file +}