Reputation: 51
I am using Sequelize to connect to Azure SQL database from Node.js. The sequelize query module is placed within a function, and the matched boolean variable is returned to the main script (app.js).
Sequelize along with the function are part of (app_functions.js)
The code snippets are pasted below:
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('[email protected]'));
Output
Matched value is: false
Executing (default): SELECT emailid FROM user_data where emailid='[email protected]'
[ { emailid: '[email protected]' } ]
DB email id is: [email protected]
True block
The function returns false
, although the True block
, inside if
condition is executed.
Also note that, the function returns the value first and then executes the definition.
How to return the correct true
value from the function containing sequelize?
Upvotes: 1
Views: 2296
Reputation: 58533
As sequelize.query
is async
behaviour and returns promise so you can do it like :
Without extra promise :
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('[email protected]').then((match) => {
console.log("Matched value is: "+ match);
});
Upvotes: 0
Reputation: 370679
Try returning a promise from loginIds
and then .then
ning the promise in app.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('[email protected]')
.then((match) => {
console.log("Matched value is: "+ match);
});
Upvotes: 1