Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

No access to this from within nested callback

No access to this from within nested callback

Problem

I have the following code:

var Company = function(app) {
    this.crypto = require('ezcrypto').Crypto;
    var Company = require('../models/company.js');
    this.company = new Company(app);
}

// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
        this.hashPassword(password, function(err, result) {
            if (err) throw err;
            console.log(this.company); // Undefined
            this.company.create(name, contact, email, result.password, function(err, result) {
                if (err) {
                    return callback(err);
                }
                return callback(null, result);
            });
        });
}

// Get company with just their email address
Company.prototype.hashPassword = function (password, callback) {
    if(typeof password !== 'string') {
        var err = 'Not a string.'
    } else {
        var result = {
            password: this.crypto.SHA256(password)
        };
    }

    if (err) {
        return callback(err);
    }
    return callback(null, result);
}
module.exports = Company;

The problem is that this.company is undefined on line 11 of that code block.

I know this is not what I think, but I'm not sure how to refactor to get access to the correct this.

Problem courtesy of: Josh Smith

Solution

so theres 2 solution's to this

first the dirty one

Company.prototype.create = function (name, contact, email, password, callback) {
    var that = this; // just capture this in the clojure 

and the clean one using bind https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

 Company.prototype.create = function (name, contact, email, password, callback) {
    this.hashPassword(password, (function(err, result) {
        if (err) throw err;
        console.log(this.company); // Undefined
        this.company.create(name, contact, email, result.password, function(err, result) {
            if (err) {
                return callback(err);
            }
            return callback(null, result);
        });
    }).bind(this));
 }
Solution courtesy of: megakorre

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

No access to this from within nested callback

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×