My bot manages server auctions, so order of commands(bids specifically) is quite important.
The commands do things like requests and DB updates during execution, and I've noticed that if I run two commands at the exact same time they run in 'parallel'(javascript parallel). This can cause some issues during validation(eg. bid price > current highest).
Is there a way to block the thread to complete a command before serving another?
I'm using the approach from the discord.js guide
index.js
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);
}
commands/command.js
const { SlashCommandBuilder } = require('@discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('<name>')
.setDescription('<desc>'),
async execute(interaction) {
// code, await db calls, etc
}
}
Thanks.
I implemented a lock on the command execution body using the async-lock npm package.
lock.js
const AsyncLock = require('async-lock');
let lock = new AsyncLock();
module.exports = lock
commands/command.js
const { SlashCommandBuilder } = require('@discordjs/builders');
const lock = require('../lock');
module.exports = {
data: new SlashCommandBuilder()
.setName('<name>')
.setDescription('<desc>'),
async execute(interaction) {
lock.acquire("", async (done) => {
try {
// code, await db calls, etc
catch {
// errors
} finally {
done();
}
}, () => {});
}
}
Feedback welcome
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.