javascript - How to callback function from another file in nodejs? -
im starting work async programming, im making nodejs application, i´ve slice code in files: index.js, ctluser.js, dao.js etc... .. index.js main file requires ctluser , ctluser require dao.js... dao connect database , execute queries...
abstracting, structure this...
index.js
var ctluser = require('./ctluser.js'); var username = ctluser.getusername('1'); console.log("return ctluser" + username);
ctluser.js
var dao = require('./dao.js'); var getusername = function(id){ var username = dao.executequery("select username tbusers id = " + id ); console.log(return dao = username); return username; }
dao.js here fine...
var mysql = require('mysql'); var executequery = function(query) { var connection = mysql.createconnection({ host : server, user : user, password : password, database : database }); connection.connect(); connection.query(query, function(err, rows, fields) { if (err) throw err; connection.end(); console.log("here in dao: " + rows[0].username); return rows[0].username; }); };
the output of $ node index.js
is:
return of ctluser: undefined return of dao: undefined here in dao: filipe tagliacozzi
im abstracting module exports everithing works fine fixed variables, database response dont..how implement callbacks in structure take username index.js?
change executequery function in dao.js module use callback:
var executequery = function(query,callback) { var connection = mysql.createconnection({ host : server, user : user, password : password, database : database }); connection.connect(); connection.query(query, function(err, rows, fields) { if (err) throw err; connection.end(); console.log("here in dao: " + rows[0].username); callback(rows[0].username); }); };
chain callback through getusername function in ctluser.js:
var getusername = function(id,callback){ dao.executequery("select username tbusers id = " + id ,function(username){ console.log("return dao =" ,username); callback(username); }); }
then consume in index.js so:
var ctluser = require('./ctluser.js'); ctluser.getusername('1',function(username){ console.log("return ctluser" + username); });
Comments
Post a Comment