Sequelize不会返回函数中的值

时间:2018-04-04 05:35:17

标签: javascript node.js sequelize.js

我正在使用Sequelize从Node.js连接到Azure SQL数据库。 sequelize查询模块放在一个函数中,匹配的布尔变量返回到主脚本(app.js)。

Sequelize和该函数是(app_functions.js)

的一部分

代码片段粘贴在下面:

app_functions.js

function loginIds(email_id) {
  var is_matched = false;

  sequelize.query("SELECT emailid FROM user_data where emailid='" + email_id + "'", {
      type: sequelize.QueryTypes.SELECT
    })
    .then(result => {
      console.log(result);
      console.log('DB email id is: ' + result[0].emailid);

      if (result[0].emailid != '') {
        console.log('True block');
        is_matched = true;
      } else {
        is_matched = false;
      }
    })

  return is_matched;
}

app.js

// Import app_functions.js
var fs = require('fs');
eval(fs.readFileSync('app_functions.js').toString());

console.log("Matched value is: "+ loginIds('xyz@gmail.com'));

输出

Matched value is: false
Executing (default): SELECT emailid FROM user_data where emailid='xyz@gmail.com'
[ { emailid: 'xyz@gmail.com' } ]
DB email id is: xyz@gmail.com
True block

该函数返回false,但执行True block条件内的if。 另请注意,该函数首先返回值,然后执行定义。

如何从包含sequelize的函数中返回正确的true值?

2 个答案:

答案 0 :(得分:1)

尝试从loginIds返回承诺,然后在.thenapp.js回复承诺:

function loginIds(email_id) {
  var is_matched = false;
  return new Promise((resolve, reject) => {
  sequelize.query("SELECT emailid FROM user_data where emailid='" + email_id + "'", {
      type: sequelize.QueryTypes.SELECT
    })
    .then(result => {
      console.log(result);
      console.log('DB email id is: ' + result[0].emailid);

      if (result[0].emailid != '') {
        console.log('True block');
        is_matched = true;
      } else {
        is_matched = false;
      }
      resolve(is_matched);
    })
  })   // Closing of Promise block
}

app.js:

loginIds('xyz@gmail.com')
  .then((match) => {
    console.log("Matched value is: "+ match);
  });

答案 1 :(得分:0)

由于sequelize.queryasync行为并返回承诺,因此您可以这样做:

没有额外承诺:

function loginIds(email_id) {
    var is_matched = false;

    return sequelize.query("SELECT emailid FROM user_data where emailid='" + email_id + "'", {
        type: sequelize.QueryTypes.SELECT
    })
    .then(result => {
        console.log(result);
        console.log('DB email id is: ' + result[0].emailid);

        if (result[0].emailid != '') {
            console.log('True block');
            is_matched = true;
        } else {
            is_matched = false;
        }
        return is_matched;
    });
}

loginIds('xyz@gmail.com').then((match) => {
    console.log("Matched value is: "+ match);
});