简体   繁体   English

从对象内部的异步回调内部调用函数

[英]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: 然后我称b为:

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

but I'm getting this error: Object #<Object> has no method 'a' . 但我收到此错误: 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) ). 问题在于外部库可能会更改上下文(使用.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();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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