我在哪里在课堂上使用诺言错了?

我正在使用这个类如下

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上validationthat.user 。 但user_exits方法抛出错误,这意味着它发现user被设置为undefined。 我已经提到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); }); };