javascript - 我怎样才能使它成为异步函数或承诺?
问题描述
我正在尝试制作一个不和谐的机器人。我使用 AkairoClient 作为框架,其中有一个设置前缀的选项。我所拥有的是以下代码:
// HANDLERS
this.commandHandler = new CommandHandler(this, {
prefix: msg => {
let prefix;
console.log('first')
con.query(`SELECT * FROM info WHERE id = ${msg.guild.id}`, (err, rows) => {
if (!err) prefix = rows[0].prefix;
console.log('Second')
});
console.log('third')
return prefix ?? '!';
},
blockBots: true,
/* Rest of code here ...*/
});
当我执行此操作时,控制台打印:
- 第一的
- 第三
- 第一的
- 第三
- 第二
- 第二
我在理解如何使其正常工作时遇到问题,因为我希望prefix
获取行的值,但在这种情况下,它会像查询完成之前prefix
一样返回undefined
解决方案
我不完全确定您的模块是如何工作的,但这将是异步等待函数的正确语法:
this.commandHandler = new CommandHandler(this, {
prefix: async msg => {
let prefix;
console.log('first');
const rows = await con.query(`SELECT * FROM info WHERE id = ${msg.guild.id}`).catch(console.log);
console.log('Second');
if (rows) prefix = rows[0].prefix;
console.log('third');
return prefix ?? '!';
},
blockBots: true,
/* Rest of code here ...*/
});
推荐阅读
- python - excel vs matplotlib 等高线图
- c++ - 如何理解 C++ 中的地址符号
- mongodb - MongoDB 将对象数组转换为单个对象
- r - as.vector中的R闪亮错误:无法将类型“闭包”强制为“字符”类型的向量
- python - 从多个文件中读取 TensorFlow Dataset 时结合 flat_map 和 zip:是否第二次从磁盘读取文件?
- python - Networkx 边缘属性
- python-3.x - 我最近进入了 python 并且无法导入任何东西
- tensorflow - keras检测不到gpu
- javascript - 跨浏览器窗口/视图的“z-index”类似方法
- multithreading - Vertx mongo 客户端通过并发更新压倒 mongodb