Home > OS >  forEach loop finishes after the last line of code executes
forEach loop finishes after the last line of code executes

Time:06-07

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);
    };

CodePudding user response:

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

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

  • Related