无法在循环外访问数组元素

时间:2019-03-20 14:55:34

标签: javascript arrays node.js asynchronous

我在node js中有这个端点并表示,将学生添加到数组中。我在请求的正文中传递了类名和一系列电子邮件。逻辑如下:

  • 使用传递的类名搜索该类是否存在。如果该类存在,则遍历电子邮件数组,搜索使用该电子邮件的用户是否存在并具有角色成员。如果它们满足要求,则将它们添加到数组中。

问题:

  • 当我尝试在循环内控制台记录阵列时,它显示出学生对象已添加到阵列中。但是,在循环之外时,我在console.log上得到了一个空数组

这是我要描述的实际代码:

const findClass = LessonClass.findOne({className: req.body.className}).exec();
findClass.then(classObject => {
       // check that each emails exists and has role member
       const studentArray = [];
       const emailBody = req.body.email;
       emailBody.forEach(email => User.findOne({email}).exec().then(userObject => {
           if(userObject.role !== 'member'){
               return res.status(400).send({
                   error: 'Only users with role member can be added to a class as students'
               });
           }
           const student = {
               email: userObject.email,
               studentName: userObject.firstName + ' '+ userObject.lastName
           };
           // add the student to the student array
           studentArray.push(student);
           console.log(studentArray); // returns student object inside array
       })
           .catch(err => {
               console.log(err);
           }));
         console.log(studentArray) //returns empty array
   })

有人帮忙吗?

1 个答案:

答案 0 :(得分:0)

因为您的代码在注销时可能仍在添加学生,请参见此代码

const findClass = LessonClass.findOne({ className: req.body.className}).exec();
findClass.then(classObject => {
  // check that each emails exists and has role member
  const studentArray = [];
  const emailBody = req.body.email;
  emailBody.forEach(email => User.findOne({email}).exec()
    .then(userObject => {
      if (userObject.role !== 'member') {
        return res.status(400).send({
          error: 'Only users with role member can be added to a class as students'
        });
      }
      const student = {
        email: userObject.email,
        studentName: userObject.firstName + ' ' + userObject.lastName
      };
      // add the student to the student array
      studentArray.push(student);
      console.log(studentArray); // returns student object inside array
      return studentArray;
    })
    .then(students => {
      console.log(students);
    }));
})

我要做的是,我删除了您的console.log并将其与第二个then链接在一起,并从您的第一个then返回了学生数组。

在javascript中,回调是非阻塞的,即它们不会阻塞执行的顺序,控制权将转到下一条语句。当您声明studentsArray并启动非同步操作(承诺)时,它没有等待执行完成就直接进入console.log语句。