我在node js中有这个端点并表示,将学生添加到数组中。我在请求的正文中传递了类名和一系列电子邮件。逻辑如下:
问题:
这是我要描述的实际代码:
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
})
有人帮忙吗?
答案 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
语句。