Houla Banada Houla Banada - 3 months ago 9
Javascript Question

Using module constructor and async

I cannot figure out how to keep the constructor scope or whatever ever you want to call it, it simply gets replaced with the global variables.

I will be calling multiple functions and each will generate different data and will set different variables;

How can I solve this?

function Foo(user, data) {
this.user = user;
this.data = data;
}
Foo.prototype.init = function(callback) {
async.series([
this.functionOne,
], function(err, result) {
callback(err, []);
});
};
Foo.prototype.functionOne = function(callback) {
console.log(this);
this.username = "abc";
callback(null);
}
module.exports = Foo;

Answer

You probably need to preserve the this value when you pass a method reference by using .bind():

function Foo(user, data) {
    this.user = user;
    this.data = data;
}
Foo.prototype.init = function(callback) {
    async.series([
        // add `.bind(this)` here to preserve value of this
        // when the function is called by async
        this.functionOne.bind(this),
    ], function(err, result) {
        callback(err, []);
    });
};
Foo.prototype.functionOne = function(callback) {
    console.log(this);
    this.username = "abc";
    callback(null);
}
module.exports = Foo;

Although, there is no reason to use the async library if you only have one async function to execute.


When you pass this.functionOne to the async library, all that is passed is a reference to the functionOne method. No association with this is preserved. Thus, when the async library calls that method later, the value of this will be wrong. You can use .bind() to "bind" the correct value of this to a new temporary stub function that you then pass to async and then when your method gets called, it will have the correct value of this.

Comments