SQlite result undefined issue in NodeJS [duplicate] - javascript

How do I get the return value from inside a value of node.js/javascript callback?
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
return "hello there is a logs";
} else {
return "there is no logs yet..."
}
})
}
var logs = get_logs();
console.log(logs);

You can't return the result from a function whose execution is asynchronous.
The simplest solution is to pass a callback :
function get_logs(cb){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
cb("hello there is a logs");
} else {
cb("there is no logs yet...)"
}
})
}
get_logs(function(logs){
console.log(logs);
});

You can't. You should instead pass another callback to your function. Something like this:
function get_logs(callback){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function(arg1) {
console.log(arg1);
});

function get_logs(callback) {
User_Log.findOne({
userId: req.user._id
}, function (err, userlogs) {
if (err) throw err;
if (userlogs) {
// logs = userlogs.logs;
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function (data) {
console.log(data);
});
Uses callbacks...

In node.js almost all the callbacks run after the function returns , so you can do something like this
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
do_something(logs)
} else {
console.log('No logs')
}
})
}

Related

mongodb nodejs store value outside connect

I need a way to store value outside mongoDB connect call:
read(object) {
let result
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
result = err;
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
assert.equal(err, null);
db.close();
result = docs;
});
}
});
return result
}
When i call this method, which is part of a class, return is called before result assignment, as normal.
Example: console.log(read(obj)) returns undefined
The idea is to store value in a variable and return might wait until connect terminate.
Is there any way to resolve this problem?
Without promise:
Call return inside find and err function:
read(object) {
let result
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
result = err;
return result; //here
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
assert.equal(err, null);
db.close();
result = docs;
return result; // here
});
}
});
}
Or set a timeout for return with enough time to wait for other process to end:
read(object) {
let result
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
result = err;
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
assert.equal(err, null);
db.close();
result = docs;
});
}
});
setTimeout(function(){ return result}, 3000); // 3secs
}
With Promise you can try the following:
function read(object) {
let result
return new Promise((resolve, reject) => {
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
reject(err);
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
db.close();
if (err) {
reject(err);
} else {
resolve(docs);
}
});
}
});
});
}
// then you can call the function and use the result like this
read(obj).then(docs => {
console.log(docs);
})
.catch(err => {
// handle error
console.log(err);
})

returning data from node mssql execute functions

I'm using mssql(Microsoft SQL Server client for Node.js) package from npm.I'm trying to execute a stored procedure residing in my sql server database.Everything works fine.However what I want to do is return the recordsets so that i can export this to be used in other module.Below is what I'm trying to do.
function monthlyIceCreamSalesReport (scope){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return;
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
}
else {
console.log(recordsets[0]); // successfully receiving the value
}
connObj.conn.close();
});
});
console.log('check for recordsets', recordsets[0]); // undefined
return recordsets[0];
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
As shown in the code snippet, since the value of recordsets[0] is undefined, exporting this function is of no use.
You can't return this way in async nature. You can get it by passing the callback function
Try to give a callback function like this
function monthlyIceCreamSalesReport(scope, callback) { // pass a callback to get value
var connObj = connConfig();
connObj.conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
connObj.req.input('Month', 4);
connObj.req.input('Year', 2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue) {
if (err) {
console.log(err);
} else {
console.log(recordsets[0]);
connObj.conn.close();
return callback(null, recordsets[0]); //return as a callback here and get that value in callback from where you called this function
}
});
});
}
var sqlServerObj = {
monICSalesReport: monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
Note: See the comment to understand the changes
recordsets[0] is undefinded, because is defined only in connObj.req.execute function scope. You may do this in this way:
function monthlyIceCreamSalesReport (scope, cb){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return cb(Error("Something wrong"));
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
connObj.conn.close();
return cb(Error("Something wrong"));
}
else {
console.log(recordsets[0]); // successfully receiving the value
connObj.conn.close();
return cb(recordsets[0]);
}
});
});
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;

Connection.query to execute

Pretty sure this is a quite noobish node.js/callback question but I can't seem to find the proper code to make it run.
This is how I invoke my node-mysql code:
var utils = require('../../config/database/utils');
exports.getResults = function(callback) {
var query = "SELECT * FROM my_table";
utils.exec(query, null, function(err, results){
if(err){
console.log(err);
callback(true);
return;
}
console.log(results);
callback(false, results);
});
};
Next is the utils file where I can't get the code work.
var pool = require('./connection');
module.exports = {
getDBConnection: function() {
pool.getConnection(function(err, connection){
if(err){
console.log(err);
return;
}
return connection;
});
},
endDBConnection: function(connection) {
connection.end(function (err) {
if(err) {
console.log(err);
callback(true);
return;
}
});
},
exec: function(query, data, callback) {
console.log(query);
this.getDBConnection(function(err, connection){
if(err){
console.log('error');
}
console.log(connection);
connection.query(query, data, function(err, results) {
if(err) {
callback(err);
}
callback(false, results);
});
this.endDBConnection(connection);
});
}
}
Code is getting OK the the exec part since the console.log(query) logs the query. But after that, the code's not running, console.log(connection); doesn't show a thing, and of course the connection.query is also not running.
I'm not sure why this is happening.
Returning a value inside a callback is meaningless. You need to pass in a callback that gets called with the value you want to return:
getDBConnection: function(callback) {
pool.getConnection(function(err, connection){
if(err){
console.log(err);
return callback(err);
}
callback(null, connection);
});
},
You should also use connection.release() instead of connection.end() since you are using a pool:
endDBConnection: function(connection) {
connection.release();
},
In exec(), you have the wrong this. It should instead be something like:
exec: function(query, data, callback) {
console.log(query);
var self = this;
this.getDBConnection(function(err, connection){
if(err){
console.log('error');
return callback(err);
}
console.log(connection);
connection.query(query, data, function(err, results) {
self.endDBConnection(connection);
if(err) {
return callback(err);
}
callback(null, results);
});
});
}

How to wait for a response from a mongo findOne query in a node/express app before using the response in following control flow

I am new to node, and also JavaScript callbacks.
I am trying to check if an account exists in mongo and then 'save it' if it doesn't and return an error if it does.
I am currently trying to figure this out outside of my express app. This is what i have..
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
if(err) throw err;
var query = { name : "www.website.com"}
findOne(db, query, function (doc) {
if(doc) {
console.log('account exists');
} else {
console.log('good to go');
}
console.dir(doc);
});
});
var findOne = function (db, query, callback) {
db.collection('accounts').findOne(query, function (err, doc) {
if(err) throw err;
db.close();
callback();
});
}
with the console.dir(doc); above returning as undefined. How do I wait for the findOne to return before using the callback to console.log or save the account?
The reason you are getting undefined is because when you call your callback your are not passing it the doc. That line should look like callback(doc).
Here is an updated version of your code with a few suggestions:
MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
if(err) throw err;
var query = { name : "www.website.com"}
findOne(db, query, function (err, doc) {
if(err) {
// something went wrong
console.log(err);
return;
}
if(doc) {
console.log('account exists');
console.dir(doc);
} else {
console.log('good to go');
}
});
});
var findOne = function (db, query, callback) {
db.collection('accounts').findOne(query, function (err, doc) {
db.close();
if(err) {
// don't use throw when in async code
// the convention is to call your callback with the error
// as the first argument (notice that I added an argument
// to the definition of your callback above)
callback(err);
}
else {
// call your callback with no error and the data
callback(null, doc);
}
});
}

Return from callback function in Javascript

How do I get the return value from inside a value of node.js/javascript callback?
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
return "hello there is a logs";
} else {
return "there is no logs yet..."
}
})
}
var logs = get_logs();
console.log(logs);
You can't return the result from a function whose execution is asynchronous.
The simplest solution is to pass a callback :
function get_logs(cb){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
cb("hello there is a logs");
} else {
cb("there is no logs yet...)"
}
})
}
get_logs(function(logs){
console.log(logs);
});
You can't. You should instead pass another callback to your function. Something like this:
function get_logs(callback){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function(arg1) {
console.log(arg1);
});
function get_logs(callback) {
User_Log.findOne({
userId: req.user._id
}, function (err, userlogs) {
if (err) throw err;
if (userlogs) {
// logs = userlogs.logs;
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function (data) {
console.log(data);
});
Uses callbacks...
In node.js almost all the callbacks run after the function returns , so you can do something like this
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
do_something(logs)
} else {
console.log('No logs')
}
})
}

Categories

Resources