在node.js中如何获取当前模块中其他模块函数的结果?

我需要其他模块function的结果在我目前的module.How我可以做到这一点。

module1.js

var module2=require('./lib/module2'); module2.getValue(); 

现在我想在getValue方法中返回'true'。如何才能到达这里。

在其他语言下面的代码将工作

 var result=module2.getValue(); 

但是在node.js中,我们必须使用callback方法来获取这个值。我该怎么做。

module2.js

 exports.getValue=function(){ console.log('getValue method called.'); return true; }; 

最后,我改变了我的module1代码,但我没有得到这个结果为true.Below是我更新的module1代码

  var module2=require('./lib/module2'); module2.getValue(); 

以下是我的确切代码

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; }); }; 

所以你有这个方法:

 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; }); }; 

有和内部callback函数。 在这种情况下, getNotificatiosById不可能从db.get返回值。 你应该读这个 。

我不知道你使用了哪个数据库系统,但是也许在API中有一个同步版本,即db.getSync 。 然后我们可以做这样的事情:

 exports.getNotificatiosById = function (notificationId) { return db.getSync(notificationId); }; 

但基本上在NodeJS中,由于执行脚本的非阻塞方式,我们几乎总是使用(并且想要使用)callback函数。 不pipe你对这个东西的知识如何,我推荐Node.jsvideo的介绍 ,其中节点的创build者解释了很多。