首页 > 解决方案 > 我怎样才能使它成为异步函数或承诺?

问题描述

我正在尝试制作一个不和谐的机器人。我使用 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

标签: javascriptnode.jsdiscord.js

解决方案


我不完全确定您的模块是如何工作的,但这将是异步等待函数的正确语法:

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 ...*/
});

推荐阅读