【问题标题】:Discord.js how to use awaitDiscord.js 如何使用 await
【发布时间】:2020-12-12 13:04:42
【问题描述】:

我想使用 await 但我不知道如何使用。我现在才用js 3个月,对函数还不是很了解。

这是我的代码

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;
}

这是我得到的错误:

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

SyntaxError: await is only valid in async function

如何获得异步作为函数

【问题讨论】:

    标签: javascript node.js async-await discord discord.js


    【解决方案1】:

    确保您指定您的functionasync function

    例如,如果您在discord.js message 事件中执行此代码:

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

    更多示例:

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

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

    您可以从官方discord.js指南here查看async / await页面

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-26
      • 2019-11-09
      • 1970-01-01
      • 2020-09-07
      • 2020-05-13
      • 2020-08-01
      • 2020-08-23
      • 2020-02-01
      相关资源
      最近更新 更多