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

标签 javascript

我想检查用户是否在我的应用程序中经过身份验证。问题是如果我用同步的方式,我不想被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/

相关文章:

javascript - If语句在javascript中只检查一次变量值

javascript - AngularJS - 如何在我的 Controller 中使用通过 Factory GET 请求检索到的数据?

javascript - 我如何找到以毫秒为单位的两次按钮点击之间的差异?

javascript - 引用错误: event is not defined on addEventListener()

javascript - window.requestFileSystem 在版本 3.3.0 中未定义

javascript - 浏览器可能不使用缓存

javascript - 如何将文本框值添加到列表中?

javascript - 获取单击元素相对于整个文档的索引

javascript - 为什么我收到未捕获的类型错误 :can't find property of undefined

javascript - 如果在 yup Schema 验证中任何字段非空,则不需要任何字段或需要所有字段