Javascript:如何在回调中设置父对象变量

bod*_*ser 3 javascript asynchronous callback mongoose node.js

我有一个在我的mongoosejs ODM模式中定义的自定义方法,它允许我生成一个salt并对给定的密码进行编码.

因为node.js加密模块是异步的,所以我必须将密码编码放入salt回调中(否则根本就没有盐,因为生成需要时间).但这不是主要问题.主要问题是我需要设置mongoosejs对象的salt和password属性.通常用"this"执行此操作,但"this"在回调中不起作用(它指的是回调而不是父对象).

那么,我怎么能从异步调用中取回我的编码密码和盐?

methods: {
    setPassword: function(password) {
        crypto.randomBytes(32, function(err, buf) {
            var salt = buf.toString('hex');
            this.salt = salt;
            crypto.pbkdf2(password, salt, 25000, 512, function(err, encodedPassword) {
                if (err) throw err;
                this.password = encodedPassword;
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用return语句,但它们没有返回任何内容......

Mic*_*ley 7

您可以将变量设置为this回调之外并在其中使用:

methods: {
    setPassword: function(password) {
        crypto.randomBytes(32, function(err, buf) {
            var self = this;
            var salt = buf.toString('hex');
            this.salt = salt;
            crypto.pbkdf2(password, salt, 25000, 512, function(err, encodedPassword) {
                if (err) throw err;
                self.password = encodedPassword;
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以绑定回调函数,以便this保留值:

methods: {
    setPassword: function(password) {
        crypto.randomBytes(32, function(err, buf) {
            var salt = buf.toString('hex');
            this.salt = salt;
            crypto.pbkdf2(password, salt, 25000, 512, function(err, encodedPassword) {
                if (err) throw err;
                this.password = encodedPassword;
            }.bind(this));
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `bind`,这是`Function`原型的一个方法.`crypto.pbkdf2(密码,盐,25000,512,函数(){...} .bind(this))`.请参阅[在MDN上绑定](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind). (2认同)