alexandernst
alexandernst

Reputation: 15089

Calling a function from inside async's callback inside an object

I have this code:

var async = require("async");

module.exports = function(vars){

    return {

        a: function(){
            console.log("a()");
        },

        b: function(){

            var self = this;

            async.series([
                function(callback){
                    ...
                    callback();
                },
                function(callback){
                    ...
                    callback();
                }
            ], function(){
                self.a(); // <------- err
            });
        }

    }
}

Then I'm calling b as:

var test = require("./test.js")({});
test.b();

but I'm getting this error: Object #<Object> has no method 'a'. Why?

Edit:

Sorry, this code actually runs fine, but I'm getting that error in my code in production.

The only difference from this example (which works correctly) and my code (which doesn't) is that my demo code is called directly:

var test = require("./test.js")({});
test.b();

while my production code is called from another library:

var my_code = require("./something.js")({});
imap_notify.on_new_mail(my_code.my_func);

Upvotes: 1

Views: 1028

Answers (2)

Luca Rainone
Luca Rainone

Reputation: 16468

The problem is that the external library probably change the context (calling your function with .bind(this)).

You can store your object in one variable and call it directly

module.exports = function(vars){

    var obj =  {

        a: function(){
            console.log("a()");
        },

        b: function(){

            // var self = this; // useless now

            async.series([
                function(callback){

                    callback();
                },
                function(callback){

                    callback();
                }
            ], function(){
                obj.a(); // <--- now it works
            });
        }

    };

    return obj;
}

Upvotes: 1

Armand
Armand

Reputation: 10264

Try this, don't know if it is valid though

var async = require("async");

var Item = function(){
    self= this;

    self.a= function(){
        console.log("a()");
    },

    self.b= function(){



        async.series([
            function(callback){
                ...
                callback();
            },
            function(callback){
                ...
                callback();
            }
        ], function(){
            self.a(); // <------- err
        });
    }
}



module.exports = function(){

    return new Item();

}

Upvotes: 0

Related Questions