gpt4 book ai didi

javascript - 检查用户是否同步认证

转载 作者:行者123 更新时间:2023-12-03 09:42:01 26 4
gpt4 key购买 nike

我想检查用户是否在我的应用程序中经过身份验证。问题是如果我用同步的方式,我不想被JS大人诅咒。我理想中想要的是有一个功能

Api.User.isAuthenticated()

我会这样运行:

if (Api.User.isAuthenticated())
{
Views.renderDashboard()
}
else
{
Views.renderLogin()
}

现在我将这个功能作为一个 promise 来实现,它工作得很好,但对于检查用户登录状态等简单的事情来说看起来过于复杂。

我使用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,以便在我们检查用户是否通过身份验证时运行自定义代码。

关于javascript - 检查用户是否同步认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31160030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com