Promise返回空值,尽管它存在于数据库中

时间:2019-08-16 18:15:46

标签: javascript node.js promise async-await sequelize.js

我正在尝试为学校创建一个数据库。在此数据库中,我要存储具有sessionId属性的类名是foreign key,它引用了session表。

类似地,我用外键students存储classId

第一行的

students数组来自其他功能完美的函数。

当我创建新会话然后存储在数据库中时,问题就在这里,并且newSession变量也获得了价值,但在类创建中却没有。它为空。 sessionId: newSession.id在这里为空。

类似的类以空sessionId的形式存储在db中,并且在创建StudentnewClass.id为空。尽管完全将类存储在DB中。

代码有什么问题?为什么在创建newClass.idnewSession.idStudentClass为空

students.forEach(async function(student) {
  //Create Session 
  let newSession = await Session.findOrCreate({
      where: {
        name: student.session,
        startDate: student.sStartDate,
        endDate: sEndDate
      }
    })
    .then(newSession => {
      return newSession;
    })
    .catch(err => console.log(err));
  //Create Class
  let newClass = await Class.findOrCreate({
      where: {
        name: student.class
      },
      defaults: {
        name: student.class,
        sessionId: newSession.id
      }
    })
    .then(newClass => {
      return newClass;
    })
    .catch(err => console.log(err));

  //Create a student.
  Student.findOrCreate({
      where: {
        id: student.id
      },
      defaults: {
        id: student.id,
        name: student.name,
        fphone: student.fphone,
        fname: student.fname,
        classId: newClass.id
      }
    })
    .then(newStudent => {
      // console.log(JSON.stringify(newStudent, null, 4)); 
    })
    .catch(err => console.log(err));
});

res.send(students);
}

1 个答案:

答案 0 :(得分:1)

根据手册findOrCreate returns an array containing the object that was found or created and a boolean that will be true,因此您使用的结果不正确。

https://sequelize.org/master/manual/models-usage.html

尝试这样的事情:

let newSession = null;
try {
  const sessionResult = await Session.findOrCreate({
    where: {
      name: student.session,
      startDate: student.sStartDate,
      endDate: sEndDate
    }
  });
  newSession = sessionResult[0];
} catch(e) {
  console.error(e);
}

此外,如果您正在使用await,则无需使用.then和.catch。改用try / catch来捕获错误。