'guild.members.fetch(); throws a error: TypeError: Cannot read properties of undefined (reading 'members') not sure why?

Im making a discord bot and im trying to get the names/id's of everyone in a server using guild.members.fetch();

However no matter what I've tried it always sends the error TypeError: Cannot read properties of undefined (reading 'members')

Heres the code im using.

const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
const guild = client.guilds.cache.get("Server_ID");
async function fetchmembs() {
    const members = await guild.members.fetch();
    return members;
}
members = fetchmembs();
console.log(members);

It always throws this Error:

const members = await guild.members.fetch();                                  
                            ^ 
TypeError: Cannot read properties of undefined (reading 'members')

I've tried almost everything I've found online to no help. I'm relatively new to coding and discord bot making so I'm not sure. I have guild Members intents enabled, put it in a async function, with a await and the start.

This is my first question so sorry if I've left stuff out or done stuff wrong Thanks in advance.



Solution 1:[1]

Put the guild declaration in the function. By the time the function is called, the client should be ready and the guilds would be cached

async function fetchmembs() {
    const guild = client.guilds.cache.get("Server_ID");
    const members = await guild.members.fetch();
    return members;
}

Solution 2:[2]

There is no guild in your bot's cache. You need to fetch it instead of getting it from guilds cache:

const guild = await client.guilds.fetch('Guild_ID');

remember to put this in an async module or await won't be available

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrMythical
Solution 2 ACGaming