0

I am trying to get all members without the bots, that works so far, but I can't access the variable outside of the function. Here's my code:

let real_members;
async function getRealMembers() {
    // load the guild
    interaction.guild.members.fetch().then(all_members => {
        // remove bots from 'real' member count
        real_members = all_members.sweep(member => !member.user.bot);
})}
await getRealMembers();
// call the function
console.log(real_members) // undefined
EckigerLuca
  • 153
  • 10
  • Use global variables – Rishab Vaigankar Sep 18 '21 at 18:25
  • put the console.log inside the function – stackoverflow Sep 18 '21 at 18:26
  • @BarbuBarbu I want to use the variable outside of the function NOT inside – EckigerLuca Sep 18 '21 at 18:28
  • @RishabVaigankar and how? – EckigerLuca Sep 18 '21 at 18:30
  • what you're trying to do, is to get some data in async mode, but console.log it in sync mode, that means, that at the moment you output the value, your data is not yet retrieved. You have to wait for it and then to output it. Your code example is without any context in order to provide you a solution. What you have right now can't work – stackoverflow Sep 18 '21 at 18:31
  • @BarbuBarbu i added some information – EckigerLuca Sep 18 '21 at 18:39
  • 3
    Since you aren't returning the promise returned by `fetch` from your `async` function, `await`ing it will do nothing. But it would be even more readable if you wouldn't use `then` there in the first place - `await` the `fetch()` call (assign its return value to `all_members`), do the `sweep` thing and `return` the result (no need for `real_members` outside). Then assign the return value of the `await getRealMembers()` function to a new `real_members` variable you declare at that spot. Voilà. – CherryDT Sep 18 '21 at 18:45

0 Answers0