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

106
Visualizações
Correct array is not fetched after async await

I have code like this-

const studentsIds: any[] = [];

        if (xlData.length > 0) {
          xlData.forEach(async (student, id) => {
            const studentExist = await User.findOne({
              email: student.email,
            });
            if (studentExist) {
              let includesStudent = await Class.findOne({
                student: { $in: [studentExist._id] },
              });
              if (!includesStudent) {
                studentsIds.push(studentExist._id);
              }
            }
          });

          res.status(200).send({
            ok: true,
            data: studentsIds,
            message: "class added successfully ",
          });
        } else {
          res.status(404).send({
            ok: false,
            message: "Oops there is  a problem with excel file",
          });
        }

If I console.log the value of studentsIds inside forEach then,it gives me an array with values which is my expectation but If I try to send the studentsIds in response, it is giving me an empty array. However If I try to set a timeout function and read studentsIds outside forEach let us suppose like 4000ms, it gives the correct array with values. Simply, async await is creating the problem here. I think code after forEach is executed first and this problem is occuring. What could be the solution for sending the correct studentsIds to response ?

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