Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

forEach loop finishes after the last line of code executes

What I am trying to do here is essentially go through a bunch of saved messages in a database, check if they still exist and if they do not, delete them, so what I’ve done is it checks if the message exists and if not it pushes it into an array of all the non-existent messages, but the code is running in the wrong order, it runs the if statement before the loop finishes. So for example it would console log the 2 before the 1. Any help would be greatly appreciated.

const {
        reactionRoleInformation,
    } = require("../database-functions/reactionroles/reactionRoleInformation");
    const {
        deleteManyReactionRoles,
    } = require("../database-functions/reactionroles/deleteManyReactionRoles");
    
    module.exports.cacheMessages = async (bot) => {
        const messageArray = await reactionRoleInformation();
        let deletedMessagesIds = new Array();
    
        messageArray.forEach(async (message) => {
            try {
                await bot.guilds.cache
                    .get(message.guild)
                    .channels.cache.get(message.channel)
                    .messages.fetch(message.id);
            } catch (err) {
                deletedMessagesIds.push(message.uniqueId);
                return;
            }
        console.log(1) 
            await bot.channels.cache.get(message.channel).messages.fetch(message.id);
        });
    
        console.log(2) 
        if (deletedMessagesIds.length !== 0) await deleteManyReactionRoles(deletedMessagesIds);
    };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.forEach() will not wait for async functions. Instead, use a combination of .map with Promise.all.

await Promise.all(messageArray.map(async (message) => {...}));

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading