首页 > 解决方案 > 如何将函数转换为函数文件夹内的异步函数

问题描述

所以我试图让机器人运行一个命令,每隔一小时左右检查一次数据库中每个人的角色。如果我没记错的话,我很确定我需要它与数据库部分异步。我不知道如何正确地用这个词来让它工作。

我知道如何正常制作异步函数,但我制作了一个函数文件夹以保持我的代码干净,并且从那里我不知道如何将一个函数转换为函数,因为正常语法不起作用。我在谷歌/查看这里时发现的大多数东西都是代码内部或消息处理程序内部的东西,而不是函数文件夹内部的东西。

问题是。我怎样才能正确地把它变成一个异步函数?

const Discord = require('discord.js');
require('dotenv').config();
const mysql = require('mysql2');
let connection;
module.exports = {
    // we need to declare the name first, then add the function
    autoRoleCheck: function (message) { 
        // find id of user who sent message
        let userId = await message.member.id;
        //find owner of the guild the message was sent in
        let owner = message.guild.ownerID        
        // Guild the user needs to have the role in
        let myGuild = bot.guilds.fetch(process.env.BOT_GUILD);
        console.log(myGuild);
    }
    // here we can add more functions, divided by a comma
}

// if you want to export only one function
// declare it normally and then export it
module.exports = autoRoleCheck;

标签: javascriptdiscord.js

解决方案


只需async在函数前面添加关键字即可使其异步。然后,您应该能够使用 await 语法。

autoRoleCheck: async function(message) {

const Discord = require('discord.js');
require('dotenv').config();
const mysql = require('mysql2');
let connection;
module.exports = {
  // we need to declare the name first, then add the function
  autoRoleCheck: async function(message) { // <-- change made here
    // find id of user who sent message
    let userId = await message.member.id;
    //find owner of the guild the message was sent in
    let owner = message.guild.ownerID
    // Guild the user needs to have the role in
    let myGuild = await bot.guilds.fetch(process.env.BOT_GUILD);
    console.log(myGuild);
  }
  // here we can add more functions, divided by a comma
}

// if you want to export only one function
// declare it normally and then export it
module.exports = autoRoleCheck;


推荐阅读