本文介绍了nodejs将值从一个模块传递到另一个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的自定义模块中,我有这个方法,它将查询数据库并查找我的数据库中是否存在用户名。我想要返回一些值,所以在上层我会知道查询结果。
in my self-defined module I have this method which will query the db and find if the username exists in my db. I want some values to be returned so in the upper level I will know the query result.
var findUserbyUsername=function(username)
{
db.users.find({email:username},function(err,result)
{
if(err|!username) {console.log('username not found'); return 0;}
else return 1;
}
);
}
module.exports.findUser=findUserbyUsername;
我会像这样调用上面的方法
in app.js I will call the above method like this
var lt=dbutil.findUser('xxxx@gmail.com');
但遗憾的是我未定义....
有谁可以帮我解决这个问题?或者其他任何建议?
but unfortunately I got undefined....Can anyone help me workaround this ? Or any other suggestions ?
推荐答案
这是一个异步代码,当然它不会返回任何东西。您可能需要以下内容:
This is an asynchronous code, of course it's not going to return anything. You might want the following:
app.js:
dbutil.findUser( 'xx@gmail.com', function( err, data ) {
if ( err ) throw err;
// Handle the datas returned "data"
} );
模块:
var findUserByUserName = function( username, callback ) {
db.users.find( { email: username }, function( err, result ) {
if ( err || !username ) {
console.log( 'username not found' );
// Call the function passed as parameter
callback( err ); // You give "undefined" as second parameter
}
else {
callback( err, result ); // You give the datas back
}
} );
} );
这篇关于nodejs将值从一个模块传递到另一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!