Anonymous function and closures in socket.io - javascript

I' have this code, know that require anonymus closure function, but don't understand how it works. If I run it there is a TypeError: undefined is not a function.
Can some one explain me anonymus closure functions with the help of this code?
mysql= require('mysql');
var connection = mysql.createConnection({});
function check_auth(input, callback){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) callback(err);
if (results.length > 0) {
callback(null,results.values); //this is the line with error
}else{
callback(null, false);
}
});
};
var io = require('socket.io').listen(5678);
io.configure(function () {
io.set('authorization', function(req, callback) {
check_auth(req.query.s, function(err, result) {
if (err) {
return console.log('error:(');
}
if(result === false) {
return callback('notauth', false);
} else {
return callback(null, result);;
}
});
});
});

You code looks good, but you have an error in your code: missing ); };
mysql= require('mysql');
var connection = mysql.createConnection({});
function check_auth(input, callback){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) callback(err);
if (results.length > 0) {
callback(null,results.values); //this is the line with error
}else{
callback(null, false);
}
}); // missing );
}; // missing };
io.configure(function () {
io.set('authorization', function(req, callback) {
check_auth(req.query.s, function(err, result) {
if (err) {
return console.log('error:(');
}
if(result === false) {
return callback('notauth', false);
} else {
return callback(null, result);;
}
});
});
});

There seems to be scoping issue in your code. You can't really call a function from another scope without referencing that scope. if you do:
io.configure(function () {
io.set('authorization', function(req, callback) {
var check_auth = function(...) {}; // <=== local defined
// then you can call this way
check_auth(...);
}
}
Since your check_auth() is defined outside, the callback of io.set() has its own scope, it doesn't know anything about check_auth(). So you have to point to the scope that has check_auth() defined. Something like this:
var me = this; // <==== scope that has check_auth defined
io.configure(function () {
io.set('authorization', function(req, callback) {
// then you can call this way
me.check_auth(...);
}
}
Or you can do closure approach by assigning check_auth to a variable and call it inside the callback. Something like this:
var check_auth = function(...) {};
io.configure(function () {
io.set('authorization', function(req, callback) {
// then you can call this way
check_auth(...);
}
}

Related

how to return array in Node.js from module

getting undefined all the time "main.js":
var dbAccess = require('../dao/dbAccess');
dbaInstance = new dbAccess();
var wordPool = dbaInstance.getWordPool();
console.log (wordPool);
and "dbAccess.js" contains:
var DatabaseAccess = function() {}
DatabaseAccess.prototype.getWordPool = function () {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
//console.log(wordPoolFromDB); -working ok
return (wordPoolFromDB);
});
}
module.exports = DatabaseAccess;
why is it not working?
DatabaseAccess.prototype.getWordPool is not returning any result.
Since you are using an asynchronous function, you need do one of these things:
a) Take a callback as parameter and invoke the callback with a result
DatabaseAccess.prototype.getWordPool = function (cb) {
RoundWord.find({}, 'words decoys', function(err, results) {
if (err) {
return cb(err, null);
}
cb(null, results);
});
}
The callback convention is: cb(error, results...)
b) Use promises
DatabaseAccess.prototype.getWordPool = function () {
return RoundWord.find({}, 'words decoys', function (err, results) {
if (err) {
throw err; // however you might want to sanitize it
}
return results;
});
}
To consume this result you will need to do it as a promise
databaseAccess.getWordPool()
.catch(function (err) {
// process the error here
})
.then(function (results) {
// something with results
});
It will work if you change to this:
var dbAccess = require('../dao/dbAccess');
dbaInstance = new dbAccess();
dbaInstance.getWordPool(function(wordPool){console.log (wordPool);});
And:
var DatabaseAccess = function() {}
DatabaseAccess.prototype.getWordPool = function (cb) {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
//console.log(wordPoolFromDB); -working ok
cb(wordPoolFromDB);
});
}
module.exports = DatabaseAccess;
If the function is Asynchronous you need to pass a callback to find to get the result:
DatabaseAccess.prototype.getWordPool = function (callback) {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
callback(err, wordPoolFromDB);
});
}
and call it as follows in main:
dbaInstance.getWordPool(function (err, wordPool) {
console.log (wordPool);
// wordPool is only available inside this scope,
//unless assigned to another external variable
});
// cannot access wordPool here

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;

NodeJS wait until mySQL query is completed

I trying to pass a object from the controller to the view. Because I want to my model separate my query's from the controller I'm loading a JS object (model).
My model looks as follows:
function MyDatabase(req) {
this._request = req;
this._connection = null;
this.init();
};
MyDatabase.prototype = {
init: function() {
this._request.getConnection( function(err, con) {
if(err) return false;
return this._connection = con;
}.bind(this));
},
getFromTable: function(table) {
this._connection.query('SELECT * FROM '+ table +';', function(err, result) {
if(err)
return false;
else if( !result )
return {error: 'Error bij het ophalen van foto\'s'};
else
return result;
}.bind(this));
}
};
module.exports = MyDatabase;
But I can't figure out how to wait until this query is completed in my controller. I've found the async module and tried multiple function like waterfall and parallel, but none of them worked for me (or I didn't use it as supposed to).
My controller currently looks as seen below:
var myDatabase = require('../dbmodel');
router.get('/', function(req, res, next) {
var db = new myDatabase(req);
async.waterfall([
function(callback) {
var db = new myDatabase(req);
var photos = db.getFromTable('photos');
callback(null, photos);
}
], function(p) {
res.locals.photos = p;
res.render('photos');
} );
});
What am I doing wrong? I do understand that NodeJS works async and doesn't wait for any function to be completed. But there must be a way this is possible. What am I doing wrong, or what do I misunderstand?
Thanks in advanced! ;)
The getFromTable method should accept a callback that will process the result of its execution.
// Accept a callback as a parameter
getFromTable: function(table, callback) {
this._connection.query('SELECT * FROM '+ table +';', function(err, result) {
if(err)
// execute the callback for a null result and an error.
callback(err, null);
else if( !result )
callback(new Error('Error bij het ophalen van foto\'s'),null);
else
// execute the callback on the result
callback(null, result);
}.bind(this));
}
The method can now be used in this manner:
// This is the callback to be passed into the method.
function processResult(err, result) {
console.log(result);
}
db.getFromTable('photos', processResult);

sails.js find queries with async.js each, parallel calls - each returning early

sails v0.11.0 (http://sailsjs.org/)
I have tried unsuccessfully to use .exec callback, promises (http://sailsjs.org/documentation/reference/waterline-orm/queries) and now async.js (https://github.com/caolan/async) to control the asynchronous flow revolving around looping over a find query. The async.each log output does not have the parallel work in it (although parallel does populate).
So if your solution works using .exec callback, promises or async.js - I will gladly take it!
I found this link gave some helpful examples of async.js (http://www.sebastianseilund.com/nodejs-async-in-practice)
Thank you for your time and assistance.
Below is my code using async:
/**
* #module :: Service
* #type {{findProfile: Function}}
*/
require('async');
module.exports = {
getProfile: function (userId, callback) {
var json = {};
json.notFound = false;
json.locations = {};
json.sports = {};
User.findOne({id: userId}).exec(function (err, user) {
if (err) {
json.notFound = true;
json.err = err;
}
if (!err) {
json.user = user;
UserSport.find({user_id: user.id}).exec(function (err, userSports) {
if (err) {
sails.log.info("userSports error: " + userSports);
}
async.each(userSports, function (userSport, callback) {
LocationSport.findOne({id:userSport.locationsport_id}).exec(function (err, locationSport) {
if (locationSport instanceof Error) {
sails.log.info(locationSport);
}
async.parallel(
[
function (callback) {
Location.findOne({id:locationSport.location_id}).exec(function (err, location) {
if (location instanceof Error) {
sails.log.info(location);
}
callback(null, location);
});
},
function (callback) {
Sport.findOne({id:locationSport.sport_id}).exec(function (err, sport) {
if (sport instanceof Error) {
sails.log.info(sport);
}
callback(null, sport);
});
}
],
function (err, results) {
if (!(results[0].id in json.locations)) {
json.locations[results[0].id] = results[0];
}
if (!(results[1].id in json.sports)) {
json.sports[results[1].id] = results[1];
}
}
); // async.parallel
}); // locationSport
callback();
}, function (err) {
sails.log.info('each');
sails.log.info(json);
}); // async.each
}); // UserSport
}
}); // User
}
}
The structure of your code is the following :
async.each(userSports, function (userSport, callback) {
// Whatever happen here, it runs asyncly
callback();
}, function (err) {
sails.log.info('each');
sails.log.info(json);
}); // async.each
You are calling the callback method, but the processing on your data is not yet done (it is running async-ly). As a result, sails.log.info is called immediatly.
You should modify your code so the callback is called once the process is done. i.e in the result of your async.parallel :
async.each(userSports, function (userSport, outer_callback) {
LocationSport.findOne({id:userSport.locationsport_id}).exec(function (err, locationSport) {
//...
async.parallel(
[
function (callback) {
// ...
},
function (callback) {
// ...
}
],
function (err, results) {
// ...
outer_callback();
}
); // async.parallel
}); // locationSport
}, function (err) {
sails.log.info('each');
sails.log.info(json);
}); // async.each

NodeJS passing an extra param to a callback

I'm a begginer in Node.JS and as a first tryout i'm implementing a small url shortening service that will get a request with an id parameter and redirect to the actual url after searching a cassandra database.
Below you can find my implementation.
var reqResponse;
app.get('/r/:id', function(req, res) {
reqResponse = res;
conn.connect(function(err, keyspace) {
if(err){
throw(err);
}
conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, redirectCallback);
});
});
function redirectCallback (err, results) {
if (err != null) {
//log
} else {
if (results.length > 0) {
results.every(function(row){
reqResponse.writeHead(config.redirectStatus, {
'Location': row[0].value
});
reqResponse.end();
return false;
});
} else {
reqResponse.send("There was a problem!");
return false;
}
}
conn.close();
return true;
}
It works fine, it does the job, but i'm having some doubts about that reqResponse "global" variable. I don't like it there.
Is there a way I could send "res" as a parameter to the redirectCallback function?
Thank you!
Yes there is: Create an anonymous function and use that to pass the parameter:
app.get('/r/:id', function(req, res) {
conn.connect(function(err, keyspace) {
if(err){
throw(err);
}
conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, function (err, results) { redirectCallback(err, res, results); } );
});
});
And your callback becomes:
function redirectCallback (err, res, results) {

Categories

Resources