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

76
Visualizações
Node.JS send results after for loop

I have a problem with my Controller in Node.Js First I find all Products related to an outfit and then I loop over all products to get the information related to that. The queries are working but I get the error "Cannot set headers after they are sent to the client" or the body is an empty Array. This is my code.

    const Outfits = require("../models/Outfits");
const Products = require("../models/Products");

module.exports = async (req, res) => {
    Outfits.find({ outfitId: req.params.id }, (error1, result) => {
        if (error1) {
            res.status(400).json({
                status: "fail",
            });
        } else {
            let productIds = result[0].productIds;
            let productsList = [];
            productIds.forEach((id) => {
                Products.find({ id: id }, (error2, products) => {
                    if (error2) {
                        res.status(400).json({
                            status: "fail",
                        });
                    } else {
                        productsList.push(products);
                        console.log(productsList);
                    }
                });
            });
            res.status(200).json({
                status: "success",
                body: productsList,
            });
        }
    });
};

Do you have any suggestions? Thank you!

about 4 years ago · Juan Pablo Isaza
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