Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda