Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
Having trouble passing through user data from mongoose inside of a nested promise chain

Having issues with mongoose promise resolve times with Discord.js. I currently have an asynchronous function to fetch a given user and one to add a given user. I know that the fetch gives the proper user object. the first returned promise is not resolving the _points field and is passing through 'undefined' immediately to the next block.

I've tried making sure these both returned promises and changing around the findUser function but nothing seems to have stuck. Any advice on how to make this promise chain work?

On command activation:

try {
    await addUser(userId, userName, guildId, guildName, createdTimeStamp, points)
        .then(() => {
            return new Promise((res, rej) => {
                const _points = findUser(userId, guildId)["points"];
                res(_points);
            });
        })
        .then((response) => {
            return new Promise((res) => {
                console.log(response);
                interaction.editReply({ content: `Current Points: ${response}`, ephemeral: true });
                res('finished');
            });
        });
} catch (e) {
    console.log(`error creating member ${e}`);
}

Mongoose functions:

const findUser = async (userId, guildId) => {
    const member = await EngagementTracking.findOne({ userId: `${userId}`, guildId: `${guildId}` }).exec();
    return await member;
};

const addUser = async (userId, userName, guildId, guildName, createdTimeStamp, points) => { 
    if (findUser(userId, guildId) !== null) return new Promise((res, rej) => {
        res("duplicate member");
    });
    const member = {
        userId: `${userId}`,
        userName: `${userName}`,
        guildId: `${guildId}`,
        guildName: `${guildName}`,
        createdTimestamp: `${createdTimeStamp}`,
        points: points
    }
    return await EngagementTracking.create(member).exec();
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

@BGPHiJACK was right and sent me down the rabbit hole of finding which promises were executing when. Altered the promise chain to ensure proper execution. For posterity and anyone running into a similar issue:

await addUser(userId, userName, guildId, guildName, createdTimeStamp, points)
    .then((response) => {
        if (response[1]) {
            return new Promise((res) => {
                interaction.editReply({ content: `Current Points: ${response[0]["points"]}`, ephemeral: true });
                res(response[0]);
            });
        } else {
            return new Promise((res) => {
                interaction.editReply({ content: `Now Tracking. Current Points: ${response["points"]}`, ephemeral: true });
                res(response);
            });
        }
    });

And the DB functions:

const findUser = async (userId, guildId) => {
    const member = await EngagementTracking.findOne({ userId: `${userId}`, guildId: `${guildId}` }).exec();
    return member;
};

const addUser = async (userId, userName, guildId, guildName, createdTimeStamp, points) => {
    const userPromise = new Promise((res) => { res(findUser(userId, guildId)); });
    return userPromise.then((response) => {
        if (response !== null) {
            return new Promise((res) =>
            { res([response, "duplicate"]); });
        } else {
            const member = {
                userId: `${userId}`,
                userName: `${userName}`,
                guildId: `${guildId}`,
                guildName: `${guildName}`,
                createdTimestamp: `${createdTimeStamp}`,
                points: points
            };
            return EngagementTracking.create(member);
        }
    });
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda