我使用的类如下
var user_class = function (body) {
this.body = body;
};
user_class.prototype.login = function () {
var that = this;
return new Promise((fullfill,reject)=>{
that.find_by_username()
.then(that.user_exists)
.then(that.check_credentials)
.then(that.generate_token)
.then(fullfill)
.catch(reject);
});
};
user_class.prototype.find_by_username = function () {
var that = this;
return new Promise((fullfill,reject)=>{
user_model
.find({username: that.body.username})
.then((user)=>{
that.user = user;
})
.then(fullfill)
.catch(reject);
});
};
user_class.prototype.user_exists = function () {
var that = this;
return new Promise((fullfill,reject)=>{
console.log(that.user);
if(that.user !== undefined) {
fullfill();
}else{
reject(new Error('null user'));
}
});
};
问题是当我调用该login
方法时,该find_by_username
函数工作得很好,我们正确设置了我从console.log
on验证的用户that.user
。但是该user_exits
方法抛出错误,这意味着它发现user
设置为未定义。我已经refered到this
到that
和仍然没有工作。
有人可以解释一下我的逻辑有什么问题以及为什么没有将用户设置为对象吗?
你的问题是上下文松散,但不像你想象的那样。这不是因为这是通过绑定覆盖的,而是因为您在传递函数时松散了上下文:
user_class.prototype.login = function () {
return new Promise((fullfill,reject)=>{
this.find_by_username()
.then(this.user_exists.bind(this))
.then(this.check_credentials.bind(this))
.then(this.generate_toke.bind(this))
.then(fullfill)
.catch(reject);
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句