0

我试图得到一个结果,但我找不到如何解决SyntaxError: await is only valid in async function

static async searchYoutube(query, message, voiceChannel) {
    await youtube.searchVideos(query, 5).catch(videos => {
      await message.say(
        ':x: There was a problem searching the video you requested!'
      );
      return;
    });
    if (videos.length < 5 || !videos) {
      message.say(
        `:x: I had some trouble finding what you were looking for, please try again or be more specific.`
      );
      return;
    }

现在,他们还推荐了前面的颜色异步,我做到了,但这标志着另一个错误

TypeError: Cannot read property 'length' of undefined

static async searchYoutube(query, message, voiceChannel) {
    await youtube.searchVideos(query, 5).catch(async (videos) => {
      await message.say(
        ':x: There was a problem searching the video you requested!'
      );
      return;
    });
    if (videos.length < 5 || !videos) {
      message.say(
        `:x: I had some trouble finding what you were looking for, please try again or be more specific.`
      );
      return;
    }
4

1 回答 1

0

广告SyntaxError: await is only valid in async function- 这几乎是不言自明的错误,但是,在这两种情况下都没有await必要message.say(...)

广告TypeError: Cannot read property 'length' of undefined– 这是因为videos第 8 行没有在任何地方定义,而是在该块内部(并且仅在该.catch块内部)。

我建议您使用与处理 结果.then相同的方式使用块。代码是异步的(并发运行),但包装函数本身不需要是..catchsearchVideosasync

static searchYoutube(query, message, voiceChannel) {
  youtube.searchVideos(query, 5)
    .then(videos => {
      if (!videos || videos.length < 5) // first check !videos, then videos.length
        message.say(`:x: I had some trouble finding what you were looking for, please try again or be more specific.`)
      else {
        ... // continue your code
      }
    })
    .catch(error => { // catch gives an error, not the result
      message.say(':x: There was a problem searching the video you requested!')
    })
}
于 2020-11-15T01:59:10.233 回答