I have this code whereby i want to check if code input data is the same in the local db. This code works fine until it gets to where i have marked as code hangs or stops here. Once the code gets to the condition it runs perfectly and assigns notifier to be true but it doesnt come out of that function and is stuck there hence the remaining part of the code is not executed. Can anyone explain to me why ? I am building an Ionic, AngularJS app.
function checklocalDB(localdb, result) {
var d= $q.defer();
var identifier = false;
var notifier = false;
// var f = function(localdb, result){
if(localdb === false) {
console.log("inside localdb false")
var insert_into_table = "INSERT INTO preferences(description, value) VALUES ('username','" + result[0].username + "'), ('token','" + result[0].token.toString() + "')";
$cordovaSQLite.execute(db, insert_into_table).then(function (res) {
console.log("executedd")
var updateDB = "UPDATE preferences SET value='true' WHERE description='registered'";
$cordovaSQLite.execute(db, updateDB).then(function (res) {
console.log("executed")
identifier = true;
notifier = true;
//d.resolve(identifier)
var query = "SELECT id, description, value FROM preferences";
$cordovaSQLite.execute(db, query).then(function (res) {
}, function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
});
}
else {
console.log("inside localdb true")
var dbNew = null;
var query = "SELECT id, description, value FROM preferences";
console.log(localdb)
$cordovaSQLite.execute(db, query).then(function (res) {
console.log("hhhhhhhhhhhhhh")
console.log(res.rows.item(2).value)
console.log(result[0].username)
if(res.rows.item(2).value != result[0].username) {
console.log("username different")
$cordovaSQLite.deleteDB("loanstreet_partners.db");
dbNew = $cordovaSQLite.openDB("loanstreet_partners.db");
$cordovaSQLite.execute(dbNew, "CREATE TABLE IF NOT EXISTS preferences (id integer primary key, description string, value string)").then(function (res) {
console.log("done")
var insert_into_table = "INSERT INTO preferences (description, value) SELECT 'registered' as registered, 'false' as value UNION SELECT 'logged_in', 'false'";
$cordovaSQLite.execute(db, insert_into_table).then(function (res) {
console.log("1st")
var insert_into_table = "INSERT INTO preferences(description, value) VALUES ('username','" + result[0].username + "'), ('token','" + result[0].token.toString() + "')";
$cordovaSQLite.execute(db, insert_into_table).then(function (res) {
console.log("2nd")
identifier = true;
notifier = true;
var updateDB = "UPDATE preferences SET value='true' WHERE description='registered'";
$cordovaSQLite.execute(db, updateDB).then(function (res) {
}, function (err) {
console.error(err);
});
});
}, function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
}
else {
notifier = true;
console.log("im here")
return notifier;
// ***code hangs or stops here***
}
}, function (err) {
console.error(err);
});
}
// ***this is never executed because it still remains false***
if(notifier === true) {
console.log(identifier)
console.log(notifier)
d.resolve(identifier)
}
return d.promise;
// watch identifier when value change then only resolve
//d.resolve(identifier)
//return d.promise;
}
Any help appreciated
Related
I am trying to add a custom validation rule to check if username exists or not. My code:
jQuery.validator.addMethod("checkexist", function(myvalue, element) {
checkifexist(function(result) {
if (result == true)
{
return true;
}
else
{
return false;
}
});
}, 'Does not exists!');
and
async function checkifexist(callback) {
const secret = keytar.getPassword('Userdata', 'MysqlPassword');
secret.then((result) => {
var mysql = require("mysql");
var connection = mysql.createConnection({
host: store.get('ip'),
port: store.get('port'),
user: store.get('username'),
password: result,
database: "database"
});
var querystring = 'SELECT * FROM `testdb`';
try
{
connection.query(querystring, (err, rows, fields) => {
if(err){
return callback("error with query", err);
}
var found;
for (var i in rows)
{
if (some check...)
{
return callback(true);
}
}
return callback(false);
});
connection.end(() => {
});
}
catch { }
});
However, if I check the valditation it correctly outputs true or false on every keypress. I still get only validation errors, though it should be a valid input.
I have a bot. It can input some text and return some word.
I would like to use MongoDB. Because Heroku can't store data.
So I add function.js that use mongoose.
console.log('data.functionswitch = ' + data.functionswitch);
console log is work fine. It can reply what i want.
return data.functionswitch;
but return data.functionswitch only return undefined when i call it in input.js/.
I have try async/await.
But it only stops working.
How can I improve it and make it work? Thank you.
-
-
2018/03/15 updated
function.js
function switchfind(id, name, callback) {
mongodb.functionSwitch.findOne({
groupid: id, functionname: name
}, function (err, data) {
if (err) {
console.log(err);
callback(null);
return;
}
else if (!data) {
console.log("No record found")
callback(null);
return;
}
console.log('date = ' + data);
console.log('data.functionswitch = ' + data.functionswitch);
callback(data.functionswitch);
return;
})
};
input.js
function parseInput(rplyToken, inputStr) {
//console.log('InputStr: ' + inputStr);
_isNaN = function (obj) {
return isNaN(parseInt(obj));
}
let msgSplitor = (/\S+/ig);
let mainMsg = inputStr.match(msgSplitor);
let trigger = mainMsg[0].toString().toLowerCase();
exports.mongoose.switchfind(mainMsg[1], mainMsg[2], function (functionswitch) {
console.log('functionswitch = ' + functionswitch)
if (functionswitch === null) {
console.log('HERE === NULL ')
}
if (functionswitch == 0) {
console.log('HERE != 0')
return;
}
else if (functionswitch != 0 ) {
console.log('HERE != 0')
if (inputStr.match(/\w/) != null && inputStr.toLowerCase().match(/\d+d+\d/) != null) return exports.rollbase.nomalDiceRoller(inputStr, mainMsg[0], mainMsg[1], mainMsg[2]);
}
})
}
update
const mongoose = require('mongoose');
let uristring = process.env.mongoURL ||
'mongodb://XXXXXXX';
mongoose.connect(uristring);
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log('Succeeded connected to: ' + uristring);
// console.log('allswitch: ' + allswitch);
}
});
var functionSchema = new mongoose.Schema({
groupid: String,
functionname: String,
functionswitch: String
});
// Compiles the schema into a model, opening (or creating, if
// nonexistent) the 'PowerUsers' collection in the MongoDB database
var functionSwitch = mongoose.model('functionSwitchs', functionSchema);
The problem in your code is that you are using findOne as it was synchronous. You cannot simply return the data, you have to use a callback.
Here is a tutorial about callbacks.
Example of what it should look like :
// The find function
function switchfind(id, name, callback) {
mongodb.functionSwitch.findOne({
groupid: id,
functionname: name
}, function (err, data) {
// Handle error
if (err) {
callback(null);
return;
}
// Handle empty data
if (data == null) {
callback(null);
return;
}
// Handle with data
callback(data.functionswitch);
})
};
// How to call it
funcX() {
switchfind(id, name, function (functionswitch) {
if (functionswitch === null) {
// Handle the error
}
// Handle the data
});
}
I am trying to validate the user before accessing the content. I have declared function globally and passing it inside the body. When I run it , I am getting error has: user doesn't exist . Please let me know where I am going wrong.
function validate(user_id){
var user_id = db.query('select user_id from user WHERE user_id = ?', [user_id],
function(error,rows) {
if (user_id != user_id) {
return false;
} else {
return true;
}
});
}
router.post('/addcustomerskills', function(req,res) {
if (validate(user_id == true)) {
return true;
// my code should execute
}else {
response.success= false;
response.mssg = "User Doesn't Exist";
res.json(response);
}
function validate(user_id, req, res){
db.query('select user_id from user WHERE user_id = ?', [user_id], function(error,rows) {
if (error || rows.length === 0) {
var response = {}
response.success= false;
response.mssg = "User Doesn't Exist";
res.json(response);
} else {
// my code should execute
return true;
}
});
}
router.post('/addcustomerskills', function(req,res) {
validate(req.body.user_id, req, res);
})
I am trying to test a constructor in node.js that uses asynchronous code, to test out a feature in it. I know the asynchronous code works because I have already ran it, before I put in the feature, as if I were an end-user. In fact, I got it thanks to some user who answered another question I had
The feature
The User constructor has a userRole member, and some async code that checks userType specified against User.userTypes. If userType found, this.userRole is set to userType. Else, exception is thrown.
The code looks like this:
async.forEachSeries(
User.userTypes,
function(user_type, callback)
{
if (user_type == userType)
{
this.userRole = user_type;
return;
}
if (user_type == User.userTypes[User.userTypes.length - 1])
{
callback(helpers.invalidData("user_role"));
return;
}
callback(null);
},
function(err)
{
if (err)
{
if (DEBUG)
{
console.log("Error from constructor...");
console.log(JSON.stringify(err, null, '\t') + "\n");
}
throw err;
}
}
);
The rest of the constructor looks like:
function User(id, email, displayName, password, userType, deleted, cb)
{
var DEBUG = true;
var error = null;
this.userID = id;
this.email = email;
this.displayName = displayName;
this.deleted = deleted;
var self = this;
async.forEachSeries(
User.userTypes,
function(user_type, callback)
{
if (user_type == userType)
{
this.userRole = user_type;
return;
}
if (user_type == User.userTypes[User.userTypes.length - 1])
{
callback(helpers.invalidData("user_role"));
return;
}
callback(null);
},
function(err)
{
if (err)
{
if (DEBUG)
{
console.log("Error from constructor...");
console.log(JSON.stringify(err, null, '\t') + "\n");
}
throw err;
}
}
);
if (User.connectedToDatabase) this._password = password;
else
{
bcrypt.genSalt(10, function (e, salt) {
bcrypt.hash(password, salt, function (e, hash) {
if (!e)
{
self._password = hash;
if (DEBUG)
{
console.log("this._password ==" + self._password);
console.log("this.userID == " + self.userID);
}
if (typeof cb === 'function')
cb(null, this);
}
else
{
console.log("Error occurred: ");
console.log(e);
if (typeof cb === 'function')
cb(e);
}
})
});
}
}
User.connectedToDatabase = false;
User.BASIC = "basic user";
User.INVENTORY_MANAGEMENT = "inventory";
User.ADMIN = "admin";
User.userTypes = [ User.BASIC, User.INVENTORY_MANAGEMENT, User.ADMIN ];
User.prototype.userID = 0;
User.prototype.email = null;
User.prototype.displayName = null;
User.prototype._password = null;
User.prototype.userRole = User.BASIC;
User.prototype.deleted = false;
User.prototype.responseObject = function() {
return {
id: this.userID,
email: this.email,
displayName: this.displayName,
userType: this.userRole
};
}
My test
I write test() function that takes parameters to pass to User. If User constructed without error, it, along with some of its members are printed to console. Else, error is printed. Here is code:
function test(email, name, pass, type)
{
try
{
var a = new User(Math.round(Math.random() * 32),
email,
name,
pass,
type
);
console.log("Test user created: " + JSON.stringify(a.responseObject(), null, '\t') + "\n");
console.log("User._password == " + a._password);
console.log("\n");
}
catch (e)
{
console.log("User could not be created.\n" + JSON.stringify(e, null, '\t') + "\n");
}
/*async.waterfall([
function(callback){
var a = new User(Math.round(Math.random * 32),
email,
name,
pass,
type);
callback(null, a);
},
function(a, callback) {
console.log("Test user created: " + JSON.stringify(a, null, '\t') + "\n");
console.log("User._password == " + a._password);
console.log("User.userID == " + a.userID);
console.log("\n");
callback(null, a);
}
],
function(err, results)
{
console.log("results of test: " + JSON.stringify(results, null, '\t'));
if (err)
{
console.log("User could not be created.\n" + JSON.stringify(err, null, '\t') + "\n");
}
})*/
}
My test cases are as follows:
userType matching first element of User.userTypes
userType matching another element of User.userTypes (I picked the last one)
userType not matching any of User.userTypes
At runtime, after new User created, User._password is default value and not the value my asynchronous code comes up with for it. I suspect I have some async-sync error, but haven't been able to fix it.
Got it fixed, thanks to #Bergi's advice.
First thing I did: in that async.forEachSeries(), I changed any instance of this to self.
Second thing I did: replaced that asynchronous code (that was working!) to synchronous code. Instead of this:
bcrypt.genSalt(10, function (e, salt) {
bcrypt.hash(password, salt, function (e, hash) {
if (!e)
{
self._password = hash;
if (DEBUG)
{
console.log("this._password ==" + self._password);
console.log("this.userID == " + self.userID);
}
if (typeof cb === 'function')
cb(null, this);
}
else
{
console.log("Error occurred: ");
console.log(e);
if (typeof cb === 'function')
cb(e);
}
})
});
I simply said: this._password = bcrypt.hashSync(password, bcrypt.genSaltSync(10)); and all was good!
I use the following code to generate a unique token for a user. Data for users is stored on MongoDB so I use promise to handle asynchronous talking to the db. In WebStorm I receive this warning : Mutable variable is accessible from closure with promise and loop. and I know there have been posts on SO about this thing, but I my case is more complicated. I know I may not even need to worry about it as I only use the last value of token but what I want to solve this issue in a correct way ?
var generateToken = function(userId) {
User.findOne({userId: userId}, function(err, user) {
if (user !== null) {
var loop = true;
while (loop) {
var token = Common.randomGenerator(20);
User.find({tokens: token}, function(err, result) {
if (err) {
loop = false;
return Promise.reject('Error querying the database');
} else {
if (result.length === 0) {
if (user.tokens === undefined){
user.tokens.push(token);
}
loop = false;
return Promise.resolve(token);
}
}
});
}
} else {
return Promise.reject('UserNotFound');
}
});
};
I came up with the following solution , is it correct ?
var generateToken = function(userId) {
User.findOne({userId: userId}, function(err, user) {
if (user !== null) {
var loop = true;
while (loop) {
var token = Common.randomGenerator(20);
(function(e){
User.find({tokens: e}, function(err, result) {
if (err) {
return Promise.reject('Error querying the database');
} else {
if (result.length === 0) {
if (user.tokens === undefined){
user.tokens = [];
}
user.tokens.push(e)
return Promise.resolve(e);
}
}
});
})(token);
}
} else {
return Promise.reject('UserNotFound');
}
});
};
NOTE As #Alex Nikulin suggested , I flipped loop to false before sending back the result of the promise. But still it's an infinite loop as it doesn't go into the User.find({tokens: e})....
Your problem is that, return statement is within function, not within loop.Your loop is infinite. I has decomposited your code.Or simply make loop false, when you resolve/reject promise. Also my code will wait each answer from User, and error will gone. And your variant with wrap function is correct (function(e){})(token).
var generateToken = function(userId) {
return new Promise(function(resolve, reject) {
User.findOne({userId: userId}, function(err, user) {
if (user !== null) {
userTokenIterator(user,resolve, reject);
} else {
reject('UserNotFound');
}
});
});
};
var addTokenToUser = function(token,user){
return new Promise(function(resolve, reject) {
User.find({tokens: token}, function(err, result) {
if (err) {
reject('Error querying the database');
} else {
var result = result.length === 0;
if (result) {
if(!user.tokens) {
user.tokens = []
}
user.tokens.push(token);
}
resolve(result);
}
});
});
};
var userTokenIterator = function (user, resolve, reject){
var token = Common.randomGenerator(20);
addTokenToUser(token, user).then(function(result){
if(result) {
resolve(token);
}else{
userTokenIterator(user,resolve, reject)
}
},function(error){
reject(error);
});
};