简体   繁体   English

onValue 多次触发

[英]onValue triggering multiple times

I'm using Node.js v18.12.1 and Discord.js v14.我使用的是 Node.js v18.12.1 和 Discord.js v14。 for developing the Discord bot.用于开发 Discord 机器人。 I need to read some data from Firebase.我需要从 Firebase 读取一些数据。 I'm confused because I'm used to how Java with Hibernate fetches data differently.我很困惑,因为我已经习惯了 Java 与 Hibernate 获取数据的方式不同。 Here, I need to use onValue() listener.在这里,我需要使用onValue()侦听器。

My onValue() acts strange.我的onValue()行为很奇怪。 Instead of just reading the data from Firebase, it skips entirely, then it triggers multiple times, each time skipping the body block of its code, and then it actually does the code after.它不只是从 Firebase 读取数据,而是完全跳过,然后触发多次,每次都跳过其代码的主体块,然后它实际执行后面的代码。

I've read somewhere on this forum that this can happen because there are more onValue() listeners that are subscribed and they are all fired up.我在这个论坛的某个地方读到,这可能会发生,因为有更多的onValue()侦听器被订阅并且它们都被激活了。 Someone mentioned I need to use the off() function somewhere "before" the onValue() .有人提到我需要在onValue() “之前”某处使用off()函数。 This confuses me because I'm using this listener in many locations.这让我很困惑,因为我在很多地方都使用这个监听器。 I need it in each command file, in execute(interaction) functions.我在每个命令文件中的execute(interaction)函数中都需要它。 You know, when you need to execute slash commands in Discord.你知道,当你需要在 Discord 中执行斜杠命令时。 I have it something like this:我有这样的东西:

async execute(interaction) {
    const infographicRef = ref(db, '/infographics/arena/' + interaction.options.getString("arena-team"));
    var imageUrl = null;
    var postUrl = null;

    onValue(infographicRef, (snapshot) => {
        imageUrl = snapshot.child("image-url").val();
        
        interaction.reply(imageUrl);
    })
},

And I planned for each command, in each command.js file to have onValue() .我计划在每个 command.js 文件中为每个命令设置onValue() I'm not sure exactly what to do.我不确定到底该怎么做。

Also, I tried to work around this with once() method, I see it in Firebase documentation, but I got the error: ref.once() is not a function .此外,我尝试使用once()方法解决此问题,我在 Firebase 文档中看到它,但我收到错误: ref.once() is not a function

It seems that after first triggering of onValue method when the body is not executed, my code in interactionCreate.js is triggered as well, it points for a command to be executed again:似乎在未执行主体时首次触发 onValue 方法后,我在interactionCreate.js中的代码也被触发,它指向要再次执行的命令:

const { Events } = require('discord.js');

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        if (!interaction.isChatInputCommand()) return;

        const command = interaction.client.commands.get(interaction.commandName);

        if (!command) {
            console.error(`No command matching ${interaction.commandName} was found.`);
            return;
        }

        try {
            await command.execute(interaction);
        } catch (error) {
            console.error(`Error executing ${interaction.commandName}`);
            console.error(error);
        }
    },
};

my bot.js (which is in my case an index file)我的bot.js (在我的例子中是一个索引文件)

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    } else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}


client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));



for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

client.once(Events.ClientReady, () => {
    console.log('Ready!');
});


client.on(Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

client.login(token);

The onValue function registers a realtime listener, that continues to monitor the value on the database. onValue函数注册了一个实时侦听器,它继续监视数据库中的值。

If you want to read a value once, that'd be done with get() function in v9 (which is the equivalent of the once method in earlier SDK versions).如果你想读取一个值一次,可以使用 v9 中的get()函数来完成(这相当于早期 SDK 版本中的once方法)。 Have a look at the code sample in the documentation on reading data once .查看一次读取数据文档中的代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正确取消订阅 Firebase 实时数据库的 onValue 侦听器 - How to properly unsubscribe to an onValue listener for Firebase Realtime Database 我在 firebase 中的“onValue”语法和“set”语法之间存在连接问题 - I have a problem with connecting between 'onValue' syntax and 'set' syntax in firebase Firebase 中的 onDataChange() 被多次触发 - onDataChange() in Firebase getting triggered multiple times Cloud Firestore 触发器运行多次 - Cloud Firestore triggers run multiple times 如何从同一个 io.Reader 读取多次 - How to read multiple times from same io.Reader Twilio 使用 DTMF 多次拨打电话和发送数字 - Twilio Make call and send digits multiple times using DTMF Flutter Firebase push onLaunch 在应用程序刷新时调用多次 - Flutter Firebase push onLaunch called multiple times on app refresh 多次导入 aws_iam_policy - importing aws_iam_policy multiple times React 触发重新渲染 - React triggering rerenders 关于 Firestore 中的事务,如果我多次写入同一个文档,这些操作会被扁平化为一次写入吗? - Regarding transactions in Firestore, if I write to the same document multiple times, will those operations get flattened to a single write?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM