简体   繁体   中英

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);

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;
}

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();

}

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