I need the result of other module function in my current module.How can i do this.
module1.js
var module2=require('./lib/module2');
module2.getValue();
Now i want that 'true' returned in the getValue method.How can i get here.
In other languages below code will work
var result=module2.getValue();
But in node.js we have to use callback method to get that value.How can i do that.
module2.js
exports.getValue=function(){
console.log('getValue method called.');
return true;
};
Finally i changed my module1 code also but i'm not getting that result as true.Below is my updated module1 code
var module2=require('./lib/module2');
module2.getValue();
Below is my exact code
server.js
var express = require('express')
, http = require('http');
var app = express();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
var cradle=require('cradle');
new(cradle.Connection)('https://mydomain.iriscouch.com/', 5984, {
cache: true,
raw: false
});
cradle.setup({
host: 'mydomain.iriscouch.com',
cache: true,
raw: false
});
var c = new(cradle.Connection);
exports.connObj=c;
var notifications=require('./lib/Notifications');
var notificationId="89b92aa8256cad446913118601000feb";
console.log(notifications.getNotificatiosById(notificationId));
Notifications.js
var appModule=require('../server');
var connectionObj=appModule.connObj;
var db = connectionObj.database('notifications');
exports.getNotificatiosById=function(notificationId){
db.get(notificationId, function (err, doc) {
console.log(doc);//im getting output for this line while running server.js file
return true;
});
};
So you have this method:
exports.getNotificatiosById = function (notificationId) {
db.get(notificationId, function (err, doc) {
console.log(doc); //im getting output for this line while running server.js file
return true;
});
};
There is and inner callback function. In this case it is impossible for getNotificatiosById to return value from inside of db.get. You should probably read this.
I don't know which database system you use, but maybe in the API there is a synchronous version, i.e. db.getSync. Then we could do something like this:
exports.getNotificatiosById = function (notificationId) {
return db.getSync(notificationId);
};
But basically in NodeJS we almost always use (and want to use) callback functions because of the non-blocking way of executing script. Regardless of your knowledge about this stuff I recommend Introduction to Node.js video in which creator of node explains alot.