Oscar Reyes
Oscar Reyes

Reputation: 4342

nodejs inherit function inside a function

im trying to inherit a function inside one, but im not sure how.

function register(Username, Password, callback)
{
    var result;

    UserModel.findOne({username: Username}, function(error, data)
    {
        if(error)
            console.log(error);

        if(data)
            result = 'already exist';

        mongoose.connection.close();

        if(!data)
        {
            var user = new UseModel(
            {
                username: Username,
                password: Password
            });

            user.save(function(error)
            {
                if(error)
                {
                    console.log(error);
                    result = 'Error';
                }

                result = 'success';
                mongoose.connection.close();
            });
        }
    });
    callback;
}

i thought that making a callback, i would be able to set a custom function in there.

i've seen someplaces that people do inherit functions inside another one, but i dont find them anymore and im trying to do them, for this code im saving a record in mongo.

so lets just say, in the other code, im calling this function with first 2 parameters, and the third would do the function i want it to do depending of the result, just like this.

this.register('myname', 'mypassword', function(
{
    if(result != 'error')
    {
        response.render('register',
        {
            'Title': Title,
            'result': result
        });
    }
}));

im not sure if the inherit is like this. but this is what im trying to do, im learning js with node so please sorry about my unexperience.

PD: im using express, swig, body-parser and mongoose modules for node.js

Upvotes: 0

Views: 72

Answers (1)

mscdex
mscdex

Reputation: 106696

Here's how your register() function might look:

function register(Username, Password, callback)
{
    UserModel.findOne({username: Username}, function(error, data)
    {
        if(error)
            return callback(error);

        if(data)
            return callback(null, 'User already exists');

        var user = new UseModel(
        {
            username: Username,
            password: Password
        });

        user.save(function(error)
        {
            if(error)
                return callback(error);
            callback(null, 'Success');
        });
    });
}

Here's how it would be used:

this.register('myname', 'mypassword', function(error, result)
{
    if (error)
      return console.error(error); // do something better here
    response.render('register',
    {
        'Title': Title,
        'result': result
    });
});

Upvotes: 1

Related Questions