2017-06-21 58 views
1

我使用的類如下我在哪裏使用諾言內部類錯了?

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驗證上that.user。但user_exits方法拋出錯誤,這意味着它發現user設置爲undefined。我已經提到thisthat仍然無法正常工作。

有人可以請解釋我的邏輯有什麼問題,爲什麼用戶沒有被設置爲對象?

+1

這裏是沒有必要的。你們在這些旅館裏放鬆情緒。然後(....綁定(那)) –

+0

你可以爲我添加一個示例。這是我第一次和班級一起使用諾言。我想我猜你的意思是在註冊函數方法鏈rt內? – georoot

+0

沒關係得到它的工作..張貼一個答案,如果你想:) – georoot

回答

2

你的問題是上下文鬆散,但不像你想象的那樣。它不是因爲通過綁定重寫,而是因爲你寬鬆的背景下,同時通過功能:

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); 
}); 
};