let embed = CacheStorage.get("TeshinEmbed") as EmbedBuilder;
let embedNext = CacheStorage.get("TeshinEmbedNext") as EmbedBuilder;
if (!embed || !embedNext) {
for (const data of DataArray) {
if (!(data.start <= Date.now() && data.end >= Date.now())) return;
let indexNext = DataArray.indexOf(data) + 1;
if (!DataArray[indexNext]) indexNext = 0;
const [goodRaw, goodNextRaw, embedDescriptionRaw, embedDescriptionNextRaw, FooterSuggestRaw] = await Promise.all([
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${data.name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${DataArray[indexNext].name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbed'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbedNext'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`generalTranslate\` WHERE id='$FooterSuggest'`),
]);
DatabaseTranslate.release();
const good = Object.values(goodRaw[0][0]).join();
const goodNext = Object.values(goodNextRaw[0][0]).join();
const embedDescriptionLocale = Object.values(embedDescriptionRaw[0][0]).join();
const embedDescriptionNextLocale = Object.values(embedDescriptionNextRaw[0][0]).join();
const FooterSuggest = Object.values(FooterSuggestRaw[0][0]).join();
const placeholders = {
"{GOOD}": good,
"{PRICE}": data.price,
"{GOODNEXT}": goodNext,
"{PRICENEXT}": DataArray[indexNext].price,
"{END}": data.end / 1000,
};
let embedDescription = embedDescriptionLocale;
let embedDescriptionNext = embedDescriptionNextLocale;
for (const placeholder in placeholders) {
embedDescription = embedDescription.replace(placeholder, placeholders[placeholder]).replace(/\\n/gm, "\n");
embedDescriptionNext = embedDescriptionNext.replace(placeholder, placeholders[placeholder]).replace(/\\n/gm, "\n");
}
embed = new EmbedBuilder().setDescription(embedDescription).setThumbnail(data.thumbnail).setColor(DiscordRandomColor());
embedNext = new EmbedBuilder()
.setDescription(embedDescriptionNext)
.setThumbnail(DataArray[indexNext].thumbnail)
.setFooter({ text: FooterSuggest })
.setColor(DiscordRandomColor())
.setTimestamp(new Date());
CacheStorage.set("TeshinEmbed", embed, 600);
CacheStorage.set("TeshinEmbedNext", embedNext, 600);
}
}
await interaction.reply({ embeds: [embed, embedNext], ephemeral: true });
},
To ensure that the interaction.reply is executed after the for of loop, you can use an asynchronous function and await the loop. Here's the modified code:
javascript
const locale = interaction.locale;
const [DatabaseGeneral, DatabaseTranslate] = await Promise.all([GetConnection("General"), GetConnection("Translate")]);
const [DatabaseLocalization, DataRaw] = await Promise.all([
getLocaleDatabase(DatabaseTranslate, "teshinTranslate", locale),
DatabaseGeneral.promise().query("SELECT * FROM `teshin`"),
]).finally(() => DatabaseGeneral.release());
const DataArray = DataRaw[0] as TeshinData[];
let embed = CacheStorage.get("TeshinEmbed") as EmbedBuilder;
let embedNext = CacheStorage.get("TeshinEmbedNext") as EmbedBuilder;
if (!embed || !embedNext) {
await (async () => {
for (const data of DataArray) {
if (!(data.start <= Date.now() && data.end >= Date.now())) continue;
let indexNext = DataArray.indexOf(data) + 1;
if (!DataArray[indexNext]) indexNext = 0;
const [goodRaw, goodNextRaw, embedDescriptionRaw, embedDescriptionNextRaw, FooterSuggestRaw] = await Promise.all([
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${data.name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${DataArray[indexNext].name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbed'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbedNext'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`generalTranslate\` WHERE id='$FooterSuggest'`),
]);
DatabaseTranslate.release();
const good = Object.values(goodRaw[0][0]).join();
const goodNext = Object.values(goodNextRaw[0][0]).join();
const embedDescriptionLocale = Object.values(embedDescriptionRaw[0][0]).join();
const embedDescriptionNextLocale = Object.values(embedDescriptionNextRaw[0][0]).join();
const FooterSuggest = Object.values(FooterSuggestRaw[0][0]).join();
const placeholders = {
"{GOOD}": good,
"{PRICE}": data.price,
"{GOODNEXT}": goodNext,
"{PRICENEXT}": DataArray[indexNext].price,
"{END}": data.end / 1000,
};
let embedDescription = embedDescriptionLocale;
let embedDescriptionNext = embedDescriptionNextLocale;
for (const placeholder in placeholders) {
embedDescription = embedDescription.replace(placeholder, placeholders[placeholder]).replace(/\\n/gm, "\n");
embedDescriptionNext = embedDescriptionNext.replace(placeholder, placeholders[placeholder]).replace(/\\n/gm, "\n");
}
embed = new EmbedBuilder().setDescription(embedDescription).setThumbnail(data.thumbnail).setColor(DiscordRandomColor());
embedNext = new EmbedBuilder()
.setDescription(embedDescriptionNext)
.setThumbnail(DataArray[indexNext].thumbnail)
.setFooter({ text: FooterSuggest })
.setColor(DiscordRandomColor())
.setTimestamp(new Date());
CacheStorage.set("TeshinEmbed", embed, 600);
CacheStorage.set("TeshinEmbedNext", embedNext, 600);
}
})();
}
await interaction.reply({ embeds: [embed, embedNext], ephemeral: true });
The main change is that the entire for of loop is wrapped in an immediately-invoked asynchronous function, which allows the await keyword to be used within the loop. This ensures that the interaction.reply call is executed after the loop has completed.
const locale = interaction.locale;
const [DatabaseGeneral, DatabaseTranslate] = await Promise.all([GetConnection("General"), GetConnection("Translate")]);
const [DatabaseLocalization, DataRaw] = await Promise.all([
getLocaleDatabase(DatabaseTranslate, "teshinTranslate", locale),
DatabaseGeneral.promise().query("SELECT * FROM `teshin`"),
]).finally(() => DatabaseGeneral.release());
const DataArray = DataRaw[0] as TeshinData[];
let embed = CacheStorage.get("TeshinEmbed") as EmbedBuilder;
let embedNext = CacheStorage.get("TeshinEmbedNext") as EmbedBuilder;
if (!embed || !embedNext) {
await (async () => {
for (const data of DataArray) {
if (!(data.start <= Date.now() && data.end >= Date.now())) {
continue; // пропускаем этот элемент
}
let indexNext = DataArray.indexOf(data) + 1;
if (!DataArray[indexNext]) indexNext = 0;
const [goodRaw, goodNextRaw, embedDescriptionRaw, embedDescriptionNextRaw, FooterSuggestRaw] = await Promise.all([
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${data.name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${DataArray[indexNext].name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbed'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbedNext'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`generalTranslate\` WHERE id='$FooterSuggest'`),
]);
DatabaseTranslate.release();
// ... остальной код ...
}
})();
}
await interaction.reply({ embeds: [embed, embedNext], ephemeral: true });
В данном случае, если условие !(data.start <= Date.now() && data.end >= Date.now()) не выполняется, то мы используем continue для пропуска текущей итерации цикла и переходим к следующему элементу в DataArray.
Вместо использования Date.parse(new Date(data.end).toString()), можно просто использовать data.end. Это потому, что data.end уже является значением в миллисекундах, которое можно использовать напрямую. Вот упрощенный вариант кода:
javascript
const locale = interaction.locale;
const [DatabaseGeneral, DatabaseTranslate] = await Promise.all([GetConnection("General"), GetConnection("Translate")]);
const [DatabaseLocalization, DataRaw] = await Promise.all([
getLocaleDatabase(DatabaseTranslate, "teshinTranslate", locale),
DatabaseGeneral.promise().query("SELECT * FROM `teshin`"),
]).finally(() => DatabaseGeneral.release());
const DataArray = DataRaw[0] as TeshinData[];
let embed = CacheStorage.get("TeshinEmbed") as EmbedBuilder;
let embedNext = CacheStorage.get("TeshinEmbedNext") as EmbedBuilder;
if (!embed || !embedNext) {
await (async () => {
for (const data of DataArray) {
if (!(data.start <= Date.now() && data.end >= Date.now())) {
continue;
}
let indexNext = DataArray.indexOf(data) + 1;
if (!DataArray[indexNext]) indexNext = 0;
const [goodRaw, goodNextRaw, embedDescriptionRaw, embedDescriptionNextRaw, FooterSuggestRaw] = await Promise.all([
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${data.name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='${DataArray[indexNext].name}'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbed'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`teshinTranslate\` WHERE id='$TeshinEmbedNext'`),
DatabaseTranslate.promise().query(`SELECT ${DatabaseLocalization} FROM \`generalTranslate\` WHERE id='$FooterSuggest'`),
]);
DatabaseTranslate.release();
const good = Object.values(goodRaw[0][0]).join();
const goodNext = Object.values(goodNextRaw[0][0]).join();
const embedDescriptionLocale = Object.values(embedDescriptionRaw[0][0]).join();
const embedDescriptionNextLocale = Object.values(embedDescriptionNextRaw[0][0]).join();
const FooterSuggest = Object.values(FooterSuggestRaw[0][0]).join();
const placeholders = {
"{GOOD}": good,
"{PRICE}": data.price,
"{GOODNEXT}": goodNext,
"{PRICENEXT}": DataArray[indexNext].price,
"{END}": data.end / 1000, // Используем data.end напрямую
};
let embedDescription = embedDescriptionLocale;
let embedDescriptionNext = embedDescriptionNextLocale;
for (const placeholder in placeholders) {
embedDescription = embedDescription.replace(placeholder, placeholders[placeholder]).replace(/\\n/gm, "\n");
embedDescriptionNext = embedDescriptionNext.replace(placeholder, placeholders[placeholder]).replace(/\\n/gm, "\n");
}
embed = new EmbedBuilder().setDescription(embedDescription).setThumbnail(data.thumbnail).setColor(DiscordRandomColor());
embedNext = new EmbedBuilder()
.setDescription(embedDescriptionNext)
.setThumbnail(DataArray[indexNext].thumbnail)
.setFooter({ text: FooterSuggest })
.setColor(DiscordRandomColor())
.setTimestamp(new Date(data.end)); // Используем data.end напрямую
}
})();
}
await interaction.reply({ embeds: [embed, embedNext], ephemeral: true });
В этом обновленном коде мы заменили Date.parse(new Date(data.end).toString()) на просто data.end, так как data.end уже содержит значение в миллисекундах, которое можно использовать напрямую. Это делает код более простым и читабельным.
Cite this conversation
“Сделай так, что interaction.reply выполнится после for of: const locale =….” Conversation with claude-3-haiku-20240307, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m851cj5ndyjzh5kvz1waa747