【问题标题】:await only valid with async function urban dictionary api discord jsawait 仅对异步函数有效城市字典 api discord js
【发布时间】:2021-05-01 09:30:47
【问题描述】:

知道如何解决这个问题吗?我尝试将异步功能放入其中,但无法使其正常工作。我不太确定如何或在何处添加异步功能,以及如何让两者一起工作。非常感谢任何帮助,这是针对不和谐的 javascript 机器人的。

client.on('message', message => {
if (message.content.startsWith(`${PREFIX}urban`)) {
  if (!args.length) {
    return message.channel.send('You need to supply a search term!');
  }

    const query = querystring.stringify({ term: args.join(' ') });
  const { list } = await fetch(`https://api.urbandictionary.com/v0/define?${query}`).then(response => response.json());
  
  if (!list.length) {
    return message.channel.send(`No results found for **${args.join(' ')}**.`);
  }

  const [answer] = list;

  const embed = new Discord.MessageEmbed()
    .setColor('#EFFF00')
    .setTitle(answer.word)
    .setURL(answer.permalink)
    .addFields(
      { name: 'Definition', value: trim(answer.definition, 1024) },
      { name: 'Example', value: trim(answer.example, 1024) },
      { name: 'Rating', value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.` },
    );
  message.channel.send(embed);
}
});

【问题讨论】:

标签: javascript api asynchronous discord


【解决方案1】:

为了运行您的await 命令,您必须将async 放在代码的顶部。有关awaitasync 工作原理的更多信息,请查看link provided by VLAZ

//put the async right before the second message, that's it
client.on('message', async message => {
if (message.content.startsWith(`${PREFIX}urban`)) {
  if (!args.length) {
    return message.channel.send('You need to supply a search term!');
  }

    const query = querystring.stringify({ term: args.join(' ') });
  const { list } = await fetch(`https://api.urbandictionary.com/v0/define?${query}`).then(response => response.json());
  
  if (!list.length) {
    return message.channel.send(`No results found for **${args.join(' ')}**.`);
  }

  const [answer] = list;

  const embed = new Discord.MessageEmbed()
    .setColor('#EFFF00')
    .setTitle(answer.word)
    .setURL(answer.permalink)
    .addFields(
      { name: 'Definition', value: trim(answer.definition, 1024) },
      { name: 'Example', value: trim(answer.example, 1024) },
      { name: 'Rating', value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.` },
    );
  message.channel.send(embed);
}
});

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2020-09-11
    • 2021-08-10
    • 1970-01-01
    • 2020-09-07
    • 2019-09-12
    • 1970-01-01
    • 2022-06-18
    • 2020-12-07
    相关资源
    最近更新 更多