-1

I'm a beginner at learning anything code. But I'm coding a Discord bot for fun and i'm trying to give it the "clear" message command but, when i run it, it give's me a message saying:

Process exited with code 1 Uncaught /Users/ayo/Desktop/verde copy/draft.js:10 await msg.channel.messages.fetch({ limit: amount }).then(messages => { ^^^^^

SyntaxError: await is only valid in async function

Here's my code:

const args = message.content.split('.clear').slice(1);
const amount = args.join(' '); 

if (!amount) return msg.reply('You haven\'t given an amount of messages which should be deleted!');
if (isNaN(amount)) return msg.reply('The amount parameter isn`t a number!'); 

if (amount > 100) return msg.reply('You can`t delete more than 100 messages at once!'); 
if (amount < 1) return msg.reply('You have to delete at least 1 message!'); 

await msg.channel.messages.fetch({ limit: amount }).then(messages => {
    msg.channel.bulkDelete(messages
)});

I'm aware it's about a async function but don't know how to fix this problem.

greened
  • 11

1 Answers1

1

The usual solution is to wrap your code in an async immediately executed function expression (IIFE):

(async function() {
     // your code goes here
})();

That said, in this code as written there's no need for you to await the .fetch call at all.

If you wanted to use async "consistently" you wouldn't use a Promise chain:

let messages = await msg.channel.messages.fetch({ limit: amount });
await msg.channel.bulkDelete(messages);
Alnitak
  • 334,560
  • 70
  • 407
  • 495