2015-02-12 105 views
1
var user = db.User.find({ where: { username: username }}).then(function(user) { 
     console.log("Authenticate"+user.authenticate(password)); 
     if (!user) { 
     return null; 
     } else if (!user.authenticate(password)) { 
      return null; 
     } else { 
     return user; 
     } 
    }).catch(function(err){ 
     return err; 
    }); 

我在節點JS上使用Sequelize JS。 我想要匹配where子句的用戶的對象。 但是當我從然後函數返回。但它進入無限循環。 我是Node Js的新手,我不知道如何在Node Js中使用Promise。 Please help mee如何在Sequelize Js中使用Promise返回實體

+0

承諾是好的你的問題是在別的地方 - 這個代碼在哪裏? – 2015-02-12 08:23:06

+0

顯示其他代碼pls,Sequelize init和model – siavolt 2015-02-12 12:04:23

回答

1

db.User.find()返回的值是一個承諾。它永遠不會是一個用戶,所以你的第一條線是不正確的。

你需要做的是從回調中調用你的處理鏈中的下一個函數then。這是Node中的標準做法。

如果您從then承諾回調中返回一些內容,它被假定爲另一個承諾,它允許您連續鏈接多個承諾(example)。這不是你想要的。

你的榜樣會更好,就像這樣:

function authentication(err, user){ 
    // Do something 
} 

db.User.find({ where: { username: username }}).then(function(user) { 
     console.log("Authenticate"+user.authenticate(password)); 
     if (!user) { 
     authentication(null, null); 
     } else if (!user.authenticate(password)) { 
      authentication(null, null); 
     } else { 
     authentication(null, user); 
     } 
    }).catch(function(err){ 
     authentication(null, user); 
    }); 

注意使用回調來確認您的身份驗證測試的結果。作爲回調的第一個參數,也是err,這是標準的Node約定。