首页 > 解决方案 > 尽管它存在于 DB 中,但 Promise 返回 null 值

问题描述

我正在尝试为学校创建一个数据库。在这个数据库中,我想存储带有引用表的属性sessionId的类名。foreign keysession

同样,我students用外键存储classId

students第一行的数组来自其他完美工作的函数。

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

类似的类以空值存储在数据库中,sessionId并且在创建时StudentnewClass.id空。虽然类完全存储在数据库中。

代码有什么问题?为什么newClass.id和在创建和newSession.id时为空StudentClass

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);
}

标签: javascriptnode.jspromiseasync-awaitsequelize.js

解决方案


根据手册,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 来捕获错误。


推荐阅读