Here's my code:
const memberGroup = ["801555002664419350", "801555002664419351", "801555002664419352", "801555002664419353", "801555002664419354", "801555002664419355", "801555002664419356", "801555002664419357", "801555002664419358", "801555002664419359", "801555002664419360", "801555002664419361", "801555002664419362", "801555002664419363", "801555002664419364"];
let namesArr = [];
for (i=0; i < queryLength2; i++) {
namesArr .push(await message.guild.members.fetch({ user: memberGroup[i] }).catch((err) => { }));
}
console.log(namesArr);
I'm using a for loop to fetch the members from the array with the api. However, this takes 7-9 seconds to return the result for the 15 ids in the memberGroup array. Doing it with 30 ids doubles the load time for up to 16 seconds. Probably the reason why it takes too long is that 90% of the users on the memberGroup array are not members of the server anymore (left the server), hence they return undefined.
Is there a way to make this faster? My plan is to list 30 users on the list/leaderboard and display their usernames using the.user.username. The list should still display the users who are not part of the server anymore. And then replace undefined values that the fetch returns for non-members with just the IDs later.
Note: I don't like to use tags here with the <@ID>.
List/leaderboard should look something like this:
Leaderboard:
- 801555002664419350
- Ben
- Mark
- 801555002664419353
- 801555002664419354
Currently, your loop is waiting for each promise to resolve, before going to the next username. You could speed up your code using await Promise.all(...)
.
The Promise.all
function takes an array of promises and run all of them at the same time. It will wait for all of them to be done before going forward with the code.
To do so, you can push each promises into an array, without calling await
on them.
Then, you can await
the Promise.all
function, by passing it they array you just build.
The output of that function will also be an array, containing each promises response in the order that they had in the promise array.
const memberGroup = [/* ... */];
let namesArrPromises = [];
for (i=0; i < queryLength2; i++) {
namesArrPromises.push(message.guild.members.fetch({ user: memberGroup[i] }).catch((err) => { }));
}
const namesArr = await Promise.all(namesArrPromises);
console.log(namesArr);
As a side note, you should avoid mixing then().catch()
with await
. If you want to catch the error, you should use a try {} catch {}
const memberGroup = [/* ... */];
let namesArrPromises = [];
for (i=0; i < queryLength2; i++) {
namesArrPromises.push(message.guild.members.fetch({ user: memberGroup[i] }));
}
try {
const namesArr = await Promise.all(namesArrPromises);
} catch (err) {
/* do something with the error */
}
console.log(namesArr);