【问题标题】:How can i resolve a problem with await in discord.js? [duplicate]如何解决 discord.js 中的 await 问题? [复制]
【发布时间】:2021-06-15 22:03:47
【问题描述】:

我正在尝试为不和谐做一个音乐机器人,我为此遵循了一个教程。 但是,当我运行时显示此错误“SyntaxError:等待仅在异步函数中有效” 这是代码:

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

我不明白我必须改变什么才能工作。

【问题讨论】:

  • 错误提示“SyntaxError: await is only valid in async function”。因此,当您执行await ytdl.getInfo(args[1]) 时,它可能在异步函数之外。你能包括代码所在的完整功能吗?

标签: javascript discord.js


【解决方案1】:

await 正在等待异步调用的响应,然后再继续执行代码。

但是在 JS 中你不能“阻塞主线程”,这就是为什么你必须使用 asyncfunction

如果您的代码已经在函数中,只需将关键字 async 放在它前面。

另一种解决方案是将您的代码封装到一个函数中,即立即调用,即

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

第三种解决方案是删除 await 关键字并使用承诺

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

【讨论】:

  • 我做了这个并且工作了,谢谢 :)
猜你喜欢
  • 2021-09-24
  • 1970-01-01
  • 2021-05-16
  • 2023-03-20
  • 1970-01-01
  • 2010-12-13
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多