[英]Node.js - return value from callback to the main function
i want to return (true,false) from this function, its returning object.. what i can do to return Boolean value ? 我想从此函数及其返回对象返回(true,false)。我该怎么做才能返回布尔值? this code is make a static method to users Module
该代码是对用户模块的静态方法
users.statics.is_username_used = function(name) {
return this.findOne({username: name}, function(error,doc){
if(is_empty(doc)){
return false;
}else{
return true;
}
});
};
Use a callback function to return the boolean. 使用回调函数返回布尔值。 For example, you can re-write the static as
例如,您可以将静态代码重写为
// assign a function to the "statics" object of your usersSchema
usersSchema.statics.is_username_used = function(name, cb) {
return this.findOne({username: name}, function(error, doc){
if (err) return cb(err, null);
return cb(null, !is_empty(doc));
});
};
const User = mongoose.model('User', usersSchema);
User.is_username_used('someusername', (err, usernameExists) => {
console.log(usernameExists);
});
In case you have Node.js 7.6+, you can use the async/await feature to make your function synchronous-like. 如果您拥有Node.js 7.6+,则可以使用async / await功能使您的函数具有同步性。
users.statics.is_username_used = async function(name) {
var doc = await this.findOne({username: name});
if (is_empty(doc))
return false;
return true;
};
Then the function is_username_used will be call with 'await' to get the boolean result: 然后,函数is_username_used将与'await'一起调用以获取布尔结果:
var isUsed = await User.is_username_used('someusername');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.