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

108
Visualizações
variable not changing outside the promise

Im trying to push the results into a variable, the variable changes when I use the push but at the end of the function when I console the variable it shows the value initialized at the beginning of the function. It would be great if someone could solve this problem.

const getProductFilters = async (req, res) => {
      var result = [];
      await Product.findById(req.params.id)
        .then(async (val) => {
          await val.filterIds.forEach(
            async (item) =>
              await Filter.findById(item)
                .then(async (itm) => {
                  await itm.variableIds.forEach(async (val) => {
                    await Variable.findById(val)
                      .then((a) => {
                        console.log("1--", result);
                        !result.includes(a.name) ? result.push(a.name) : "";
                      })
                      .catch((err) => console.log(err));
                  });
                })
                .catch((err) => console.log(err))
          );
          console.log("2--", result);
        })
        .catch((err) => console.log(err));
    };

I'm getting this result:

2-- []
1-- []
1-- [ 'size' ]
1-- [ 'size', 'color' ]
1-- [ 'size', 'color' ]
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