【发布时间】:2013-03-22 03:50:06
【问题描述】:
我需要当前模块中其他模块功能的结果。我该怎么做。
模块1.js
var module2=require('./lib/module2');
module2.getValue();
现在我希望在 getValue 方法中返回 'true'。我怎样才能到达这里。
以下代码在其他语言中也可以使用
var result=module2.getValue();
但在 node.js 中,我们必须使用回调方法来获取该值。我该怎么做。
module2.js
exports.getValue=function(){
console.log('getValue method called.');
return true;
};
最后我也更改了我的 module1 代码,但我没有得到正确的结果。下面是我更新的 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;
});
};
【问题讨论】:
-
var result=module2.getValue();只要你的方法是同步的就可以了。 -
@generalhenry var result=module2.getValue();控制台.log(结果); //我试过这段代码,但它总是将结果显示为未定义。
-
奇怪,试试 module1
console.dir(module2);和console.log(module2.getValue.toString());看看你得到了什么。 -
@generalhenry 第一个我得到 [object object] ...第二个我得到以下函数........ function(){ console.log('getValue 方法调用。' );返回真; };
-
@generalhenry..有没有其他方法可以得到这个结果。