sk3
sk3

Reputation: 25

Discord.js how to use await

I want to use await but I don't know how to. I've only been using js for 3 months now and I don't know much about functions.

Here's my code

switch (args[1]) {
 case 'instagram':
  const accname = args[2];

  if (!accname) {
   return msg.reply('Include an Instagram handle');
  }

  const url = `https://instagram.com/${accname}/?__a=1`;
  const accinfo = await fetch(url).then((url) => url.json());

  console.log(accinfo);
  break;
}

and this is the error I get:

const accinfo = await fetch(url).then(url => url.json());
                ^^^^^

SyntaxError: await is only valid in async function

How do I get async as a function

Upvotes: 1

Views: 128

Answers (1)

Lioness100
Lioness100

Reputation: 8412

Make sure you specify that your function is an async function

For example, if you are executing this code within the discord.js message event:

client.on('message', async (message) => {
   // your code...

Further examples:

const log = () => {
  await console.log('This will return an error')
};

log()

log = async() => {
  //  ^^^^^
  await console.log('However this, will not')
};

log()

You can view the async / await page from the official discord.js guide here

Upvotes: 3

Related Questions