Sequelize-NodeJS-返回o函数未定义

时间:2018-11-08 18:40:11

标签: node.js sql-server sequelize.js

我试图了解如何修复代码,因为我的函数未定义返回。我正在用Sequelize和NodeJS编写代码。

exports.getCreditsStudent = function(sgecode,collections,grade,year){
mssql.query('SELECT total FROM [dbo].[creditosAvulsos] WHERE codsge = $sgecode1 and nivelensino_idnivelensino = $collections1 and produto_idproduto = $grade1 and ano = $year1',
{ bind:{sgecode1: sgecode, collections1: collections, grade1: grade, year1: year}, type: mssql.QueryTypes.SELECT})
.then(total => {
    return total
  })

}

然后在Service.js上调用此函数,如下所示:

examples = db.getCreditsStudent(sgecode,collections,grade,year);

问题出在哪里以及如何解决?

谢谢。

1 个答案:

答案 0 :(得分:0)

函数getCreditsStudent实际上不返回任何内容。相反,它仅定义了一个异步过程。您需要返回已定义的promise,然后使用async / await或promise链来使用结果。

exports.getCreditsStudent = function(sgecode,collections,grade,year){
  return mssql.query('SELECT total FROM [dbo].[creditosAvulsos] WHERE codsge = $sgecode1 and 
  nivelensino_idnivelensino = $collections1 and produto_idproduto = $grade1 and ano =  $year1',
  { bind:{sgecode1: sgecode, collections1: collections, grade1: grade, year1: year},
  type: mssql.QueryTypes.SELECT})
  .then(total => {
      return total
    })
}

然后在异步函数中可以执行

examples = await db.getCreditsStudent(sgecode,collections,grade,year);

或者您可以使用

db.getCreditsStudent(sgecode, collections, grade, year)
.then(value => {
   examples = value;
   // whatever you want to do with examples...
});