如何在函数文件夹中将函数转换为异步函数



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

我知道如何正常地制作异步函数,但我制作了一个函数文件夹来保持代码的整洁,从那里我不知道如何将一个函数变成一个函数,因为正常的语法不起作用。当我在谷歌/搜索这里时,我发现的大多数东西都是代码内部或消息处理程序内部的东西,而不是函数文件夹内部的东西。

问题是。我如何才能正确地将其命名为异步函数?

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;

我不知道为什么要将函数封装在module.exports中,然后再导出。

试着先定义函数,然后导出它

const Discord = require('discord.js');
require('dotenv').config();
const mysql = require('mysql2');
let connection;
// we need to declare the name first, then add the function
async function autoRoleCheck(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 = await 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);
}


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

我已经在函数中的所有内容中添加了waiting,因为我不知道实际访问数据库的是什么。实际上,你不需要等待任何消息,因为当你调用它时,你会把它传递给函数。

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

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;

在对象中定义函数的最佳方法是使用以下语法:

let someObj = {
someFunction(arg1, arg2) {
//code
},
async someAsyncFn(arg1, arg2) {
//async code
}
}

执行非常容易:

someObj.someFunction(arg1, arg2)
someObj.someAsyncFunction(arg1, arg2)

相关内容

  • 没有找到相关文章

最新更新