所以我试图让机器人运行一个命令,每隔一小时左右检查一次数据库中每个人的角色。如果我没记错的话,我很确定我需要它的数据库部分是异步的。我不知道如何正确地表达它以使其正常工作。
我知道如何正常创建异步函数,但我正在创建一个函数文件夹以保持我的代码干净,从那里我不知道如何将一个函数转换为函数,因为正常语法不起作用。我在谷歌/查看这里时发现的大多数东西都是用于代码内部或消息处理程序内部的东西,而不是用于函数文件夹内部的东西。
问题是。我如何才能正确地将其描述为异步函数?
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;
答案 0 :(得分:0)
只需在函数前添加 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;
答案 1 :(得分:0)
我不知道你为什么把这个函数包装在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 };
我已将等待添加到函数中的所有内容中,因为我不知道此处实际访问数据库的是什么。您实际上不需要等待消息的任何内容,因为您在调用它时将其传递给函数。 (除非您正在传递承诺,否则这些等待会很方便)。
答案 2 :(得分:0)
在对象中定义函数的最佳方式是使用以下语法:
let someObj = {
someFunction(arg1, arg2) {
//code
},
async someAsyncFn(arg1, arg2) {
//async code
}
}
执行起来超级容易:
someObj.someFunction(arg1, arg2)
someObj.someAsyncFunction(arg1, arg2)