代码之家  ›  专栏  ›  技术社区  ›  Evanss

将调用localstorage的函数转换为async wait

  •  0
  • Evanss  · 技术社区  · 6 年前

    我有一个URL,用户在使用auth0签名后也会返回该URL。当他们点击这个网址时,我打电话给 auth.handleAuthentication()

    在我的反应页面组件中:

    class AuthCallback extends React.Component {
      componentDidMount() {
        auth.handleAuthentication();
      }
    

    这是调用的函数:

      handleAuthentication() {
        this.auth0.parseHash((err, authResult) => {
          if (authResult && authResult.accessToken && authResult.idToken) {
            this.setSession(authResult);
          } else if (err) {
            console.error(err);
          }
        });
      }
    
     setSession(authResult) {
        let expiresAt = JSON.stringify(
          authResult.expiresIn * 1000 + new Date().getTime(),
        );
        localStorage.setItem('access_token', authResult.accessToken);
        localStorage.setItem('AUTH_TOKEN', authResult.idToken);
        localStorage.setItem('expires_at', expiresAt);
      }
    

    之后我需要异步做一些事情 handleAuthentication() setSession() 已经完成了手术。

    我只是想补充一下 async await 但代码似乎是同步运行的。

    class AuthCallback extends React.Component {
      async componentDidMount() {
        await auth.handleAuthentication();
        // DO STUFF
        window.location.hash = '';
        window.location.pathname = '/auth-callback-login';
      }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   onecompileman    6 年前

    刚刚完成了你需要等待返回承诺的功能

    handleAuthentication() {
     return new Promise((resolve, reject) => {
       this.auth0.parseHash((err, authResult) => {
         if (authResult && authResult.accessToken && authResult.idToken) {
           this.setSession(authResult);
           return resolve(authResult);
       } else if (err) {
         console.error(err);
         reject(err);
       }
      });
     });
    

    那么你可以这样做

    class AuthCallback extends React.Component {
      async componentDidMount() {
      await auth.handleAuthentication();
      // DO STUFF
      window.location.hash = '';
      window.location.pathname = '/auth-callback-login';
    

    }