2016-09-29 38 views
1

我正在使用nodejs + Express作爲我的後端服務。如何正確獲取承諾返回的值?

我有一個authenHandler.js文件,以幫助sequelize認證:

module.exports = { 
    isAuthenticated: function(data) { 
    models.Users.find(data) 
     .then(function(user) { 
     if (user) { 
      return true; 
     } else { 
      return false; 
     } 
     }); 
    } 
} 

當我使用app.js這個輔助功能:

app.use(function(req, res, next) { 
     // process to retrieve data 
     var isAuthenticated = authProvider.isAuthenticated(data); 
     console.log(isAuthenticated); 
     if (isAuthenticated) { 
      console.log("auth passed."); 
      next(); 
     } else { 
      var err = new Error(authenticationException); 
      err.status = 403; 
      next(err); 
     } 
    } 
}) 

這總是轉到else語句因爲isAuthenticated打印行總是返回undefined。看起來promise在調用if-else語句之後返回值。

我不確定如何連接authenHandler.js和app.js.什麼是最好的方式來做到這一點?

+0

你有使用require('authenHandler.js')嗎? –

+0

請參閱副本中的「承諾陷阱」。 –

+0

通過在isAuthenticated函數中保留相同的參數req,res和next,並且可以處理以在函數中檢索日期本身,您可以使用isAuthenticated函數作爲中間件。 –

回答

1

改變它返回的承諾

isAuthenticated: function(data) { 
    return models.Users.find(data) 
     .then(function(user) { 
     if (user) { 
      return true; 
     } else { 
      return false; 
     } 
     }); 
    } 

,然後消耗的承諾

authProvider.isAuthenticated(data) 
.then((result =>{ 
var isAuthenticated = result; 
    console.log(isAuthenticated); 
     if (isAuthenticated) { 
      console.log("auth passed."); 
      next(); 
     } else { 
      var err = new Error(authenticationException); 
      err.status = 403; 
      next(err); 
     } 
})) 
+0

如果在isAuthenticated函數中,我也有一個檢查: if(!data){return false;} 在我調用sequelize promise之前?我應該如何將數據驗證包裝到承諾中? 謝謝! – jamesdeath123

+0

以及結果=> {}是什麼意思?我不認爲它在nodejs中有效的語法? – jamesdeath123

+0

()=> {}是ES6箭頭功能,其可被寫爲 '功能(){}' 中的舊版本。節點支持箭頭功能。 (請參閱版本兼容性)。 不明白你的第一個問題。 – theAnubhav

1

您app.js是錯誤的,isAuthenticated回報承諾不返回布爾

您需要修改這樣的app.js

app.use(function(req, res, next) { 

     // process to retrieve data 
     authProvider.isAuthenticated(data) 
      .then(function(isAuthenticated) { 
      if (isAuthenticated) { 
       console.log("auth passed."); 
       next(); 
      } 
      else { 
       var err = new Error(authenticationException); 
       err.status = 403; 
       next(err); 
      } 
      }); 
    } 
}) 
+0

看起來我還需要更改authProvider.isAuthenticated()以使其返回承諾?我應該怎麼做? – jamesdeath123

+0

@ jamesdeath123您應該在models.Users.xxxxx之前添加「返回」 –