【问题标题】:Promise returns null value although it exist in DB尽管它存在于 DB 中,但 Promise 返回 null 值
【发布时间】:2019-08-17 18:44:04
【问题描述】:

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

同样,我用外键classId存储students

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

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

类似的类存储在数据库中,sessionId 为空,在创建 Student 时,newClass.id 为空。虽然类完全存储在数据库中。

代码有什么问题?为什么 newClass.idnewSession.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);
}

【问题讨论】:

  • 你用的是什么ORM?
  • 是sequelize.js
  • 至少:你使用await,不要使用.then()await 的重点是不必使用 then/catch 语法,而是将代码编写为“普通”代码,带有函数返回和可选的 try/catch 包装。 let newSession = await Session.findOrCreate({...}) 并完成:newSession 将是 Session.findOrCreate 产生的任何承诺解决方案。

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


【解决方案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 来捕获错误。

【讨论】:

  • 不客气 :) 不知道谁投了反对票,但请你投赞成票
  • 我把自己卷入了回调地狱。哈哈!你很快解决了!
  • 当我尝试upvode Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.时这是错误的
猜你喜欢
  • 1970-01-01
  • 2018-03-09
  • 2016-03-22
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
相关资源
最近更新 更多