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

288
Visualizações
Respond from method in controller without req, res from Express

I have a method that performs an update in Mongo but I do not have access to "res" and "res" since it is a method that I will use on more than one occasion.

My problem is when responding to the update as I try with a return but it doesn't work as the request never completes. Do you know how I can answer then?

This method calls the method that will be reused several times:

let item = (req, res = response ) => {

        const { id } = req.params;
    
        const { status, user, ...data } = req.body; 
        data.user = req.uid; 
        data.expenditure = null;

        let item = {
                concept: data.concept,
                revenue: data.revenue,
            'createdBy': {
                    uid: req.uid,
                    username: req.user.username,
                },
                description: data.description
         }
            
        createNewItem( id, item );
}

And this is the method to reuse several times that does not have "req" or "res":

const createNewItem = async ( id, item ) => {

       try {

        let pettycash = await PettyCash.findByIdAndUpdate( id,
            {
                $push: { 
                    'items': {
                      $each: [item],
                    }
                }
            },{ new: true }

        );

    return { err: null, status: 200, pettycash };
        
             
    } catch (err) {
        return { err: err.toString(), status: 500, data: null };         
    } 
}

Although the process is correct return { err: null, status: 200, pettycash }; doesn't finish the request so POSTMAN never finishes and you keep waiting for some response.

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Okay so two options.

One pass res to function as argument which you don't want and is not a good idea because it violates single responsibility rule for a function.

You add await so that controller waits for the function execution to complete. To do this make your controller async. This is generally a good idea. You let controller do its work meanwhile your createNewItem only have single responsibility of creating an item.

let item = async (req, res = response ) => {

    const { id } = req.params;

    const { status, user, ...data } = req.body; 
    data.user = req.uid; 
    data.expenditure = null;

    let item = {
            concept: data.concept,
            revenue: data.revenue,
        'createdBy': {
                uid: req.uid,
                username: req.user.username,
            },
            description: data.description
     }
        
    await createNewItem( id, item );

    // send response back
 }
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