javascript - 如何将函数转换为函数文件夹内的异步函数
问题描述
所以我试图让机器人运行一个命令,每隔一小时左右检查一次数据库中每个人的角色。如果我没记错的话,我很确定我需要它与数据库部分异步。我不知道如何正确地用这个词来让它工作。
我知道如何正常制作异步函数,但我制作了一个函数文件夹以保持我的代码干净,并且从那里我不知道如何将一个函数转换为函数,因为正常语法不起作用。我在谷歌/查看这里时发现的大多数东西都是代码内部或消息处理程序内部的东西,而不是函数文件夹内部的东西。
问题是。我怎样才能正确地把它变成一个异步函数?
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;
解决方案
只需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;
推荐阅读
- c# - 尝试使用 GDAL/OGR 打开 shapefile 时,“gdalconst_wrap”dll 丢失或无法读取
- python - 序列化字段时如何获取字符串片段(Django / DRF)
- spring - 在初始化整个上下文或执行服务器启动后,有什么方法可以初始化 spring bean?
- css - 有没有办法制作三角HR?
- python - 将日期从整数转换为日期格式
- c# - 在 while 循环中不更新值
- docker - Docker compose 不会启动 selenium 网格
- php - 表单提交奇怪的行为
- mysql - 如何使这个 sql INSERT SELECT 查询在空表上工作?
- database - 我可以在 MongoDB 中将 elemMatch 与点表示法结合使用吗?