Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!