0

I'm trying to do a music bot for discord and I follow a tutorial for this. But, when I run show this error "SyntaxError: await is only valid in async function" This is the code:

    const songInfo = await ytdl.getInfo(args[1]);
const song = {
  title: songInfo.videoDetails.title,
  url: songInfo.voiceDetails.video_url,
};

I can't understand what I have to change to works.

  • The error says "SyntaxError: await is only valid in async function". So when you do `await ytdl.getInfo(args[1])`, it's probably outside of an async function. Can you include the full function that the code is in? – programmerRaj Jun 15 '21 at 13:52

1 Answers1

2

await is waiting for the response of an asynchronous call before continuing the code.

However in JS you cannot "block the main thread", which is why you have to use an asyncfunction

If your code is already in a function just put the keyword async in front of it.

An other solution is to encapsulate your code into a funciton thas is called immediatly ie

(async () =>  {
   const songInfo = await ytdl.getInfo(args[1]);
   const song = {
     title: songInfo.videoDetails.title,
     url: songInfo.voiceDetails.video_url,
   };
})();

A 3rd solution is to drop the await keyword and work with promises

  ytdl.getInfo(args[1]).then(songInfo => {
     const song = {
       title: songInfo.videoDetails.title,
       url: songInfo.voiceDetails.video_url,
     };
  });
CharybdeBE
  • 1,791
  • 1
  • 20
  • 35