Javascript 我在课堂上使用承诺会有什么问题?
我使用的类如下Javascript 我在课堂上使用承诺会有什么问题?,javascript,node.js,javascript-objects,Javascript,Node.js,Javascript Objects,我使用的类如下 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)
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
函数工作正常,用户设置正确,我从控制台对其进行了验证。但是user\u exits
方法抛出错误,这意味着它发现user
被设置为未定义。我已经提到了这个
到那个
,但仍然不起作用
有人能解释一下我的逻辑出了什么问题,以及为什么用户没有被设置为object吗?你的问题是没有上下文,但不像你想的那样。这并不是因为这是通过绑定重写的,而是因为在传递函数时会丢失上下文:
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);
});
};
这在这里是不必要的。而你在thens中失去了上下文。那么你能给我加一个例子吗。这是我第一次在课堂上使用promise。我想我猜你的意思是在注册函数方法链rt内?不要紧,让它工作。。如果需要,请发布答案:)