简体   繁体   中英

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 ? 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.

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:

var isUsed = await User.is_username_used('someusername');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM