使用模块构造函数和异步

时间:2016-08-25 23:33:26

标签: javascript node.js asynchronous

我无法弄清楚如何保持构造函数范围或任何你想要调用它的东西,它只是被全局变量替换。

我将调用多个函数,每个函数将生成不同的数据并设置不同的变量;

我该如何解决这个问题?

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;

1 个答案:

答案 0 :(得分:1)

使用this传递方法引用时,可能需要保留.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;

但是,如果只有一个异步函数可以执行,则没有理由使用异步库。

当您将this.functionOne传递给异步库时,传递的所有内容都是对functionOne方法的引用。不保留与this的关联。因此,当异步库稍后调用该方法时,this的值将是错误的。您可以使用.bind()this的正确值绑定到新的临时存根函数,然后将其传递给异步,然后在调用方法时,它将具有正确的值{{ 1}}。