[英]Check if user is authenticated synchronously
我想檢查用戶是否在我的應用程序中通過了身份驗證。 問題是如果我以同步方式使用它,我不希望被JS Lord詛咒。 我理想中想要的是具有功能
Api.User.isAuthenticated()
我會這樣運行:
if (Api.User.isAuthenticated())
{
Views.renderDashboard()
}
else
{
Views.renderLogin()
}
現在,我將此功能實現為一個諾言,它可以正常工作,但是看起來很復雜,例如檢查用戶登錄狀態之類的簡單事情。
我使用qwest庫發出XHR請求。 它返回promise,代碼如下所示:
Api.User.isAuthenticated = function(token)
{
return qwest.get('/session', token)
}
Api.User.isAuthenticated(token)
.then(function (response) {
//
})
.catch(function (e, response) {
//
});
我應該如何解決這個問題?
如果您的身份驗證方法需要異步,則可以嘗試使用回調:
Api.User.checkAuthentication = function(token, callback) {
qwest.get('/session', token).then(function (response) {
// Check your response here, send true or false to the callback as appropriate
callback(true);
})
.catch(function (e, response) {
// You should probably notify the user of the error here, that it wasn't
// just an invalid username/password combo
callback(false);
});
}
Api.User.checkAuthentication('token', function (authenticated) {
if (authenticated) {
Views.renderDashboard();
} else {
Views.renderLogin();
}
})
整個方法可以放入一個函數,例如checkAuth()
,可以在需要時調用。 您可以更進一步,並將回調傳遞給checkAuth,以便在我們檢查用戶是否通過身份驗證時運行自定義代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.