-1

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 ?

0 Answers0