首页 > 解决方案 > 使用 oath 时 Amplify.Hub 登录处理程序中的竞争条件

问题描述

示例代码:

Hub.listen('auth', event => {
  const { event: type, data } = event.payload;

  if (type === 'signIn') {
    const session = data.signInUserSession;
    console.log('SESSION', data.signInUserSession);
    setTimeout(() => {
      console.log('SESSION', data.signInUserSession);
    }, 100);
  }
});

使用 oath 时,提供程序重定向到我的应用程序后,集线器会触发一个signIn事件。但是,该signInUserSession属性是null触发事件的时间,但会在一段时间后(100 毫秒内)获得一个值。直接使用时似乎不会出现这种情况Auth.signIn(email, password)signInUserSession触发事件时填充。

这里发生了什么,我该如何解决?目前,我在代码中有一个明确的延迟,这是一个可怕的黑客攻击。

标签: javascriptaws-amplify

解决方案


也许 JavaScript 等待填充值的旧方法有助于确保代码不会失败,即使填充值的时间比预期的要长。

这是我通常在没有其他选项可用时使用的示例代码。

waitForValue(){
    if(myVar!= null && typeof myVar !== "undefined"){
        //value exists, do what you want
        console.log(myVar)
    }
    else{
        setTimeout(() => {this.waitForValue()}, 100);
    }
}

您可以根据需要重构此示例代码。

或者,AWS Amplify 也有其他方法来获取当前登录的用户会话。例如Auth.currentAuthenticatedUser()Auth.currentSession()返回承诺。它们可以像这样使用

private async getUser(){
    let user = null;
    try {
      user = await Auth.currentAuthenticatedUser();
      //console.log(user);
    } catch (err) {
      //console.log(err);
    }
    //return user;
  }

推荐阅读