title: Keycloak | Cannot await on updateToken() in async function
body: <p>We are developing Spring application with React/Redux frontend. We successfully integrated it with Keycloak authentication service. However, we encountered unwanted behaviour after access token timed out. Our restMiddleware looks like this (simplified):</p>
  
  <pre class="lang-js prettyprint-override"><code>    function restMiddleware() {
      return (next) =&gt; async (action) =&gt; {
         try{
  
              await keycloak.updateToken(5);
  
              res = await fetch(restCall.url, {
                  ...restCall.options, ...{
                      credentials: 'same-origin',
                      headers: {
                          Authorization: 'Bearer ' + keycloak.token
                      }
                  }
              });
  
         }catch(e){}
      }
  </code></pre>
  
  <p>The problem is, that after token expires and updateToken() is executed, async function does not stop and invokes fetch() immediately, before new access token is received. This of course prevents fetch request from succeeding and causes response with code 401. updateToken() returns a Promise, so I see no reason why await would not work on it, which certainly is happening.</p>
  
  <p>I confirmed that function in <code>updateToken().success(*function*)</code> will execute after successful token refresh and placing fetch() inside it would solve the problem, but because of our middleware construction I cannot do that. I developed this workaround:</p>
  
  <pre class="lang-js prettyprint-override"><code>    function refreshToken(minValidity) {
  
          return new Promise((resolve, reject) =&gt; {
  
              keycloak.updateToken(minValidity).success(function () {
                  resolve()
              }).error(function () {
                  reject()
              });
          });
      }
  
      function restMiddleware() {
      return (next) =&gt; async (action) =&gt; {
         try{
              await refreshToken(5);
  
              res = await fetch(restCall.url, {
                  ...restCall.options, ...{
                      credentials: 'same-origin',
                      headers: {
                          Authorization: 'Bearer ' + keycloak.token
                      }
                  }
              });
  
         }catch(e){}
      }
  </code></pre>
  
  <p>And it works, but it is not elegant.</p>
  
  <p>The question is: why the first solution didn't worked? Why I cannot await on updateToken() and have to use updateToken().success() instead?</p>
  
  <p>I suspect this might be a bug and to confirm this is the main purpose of this question.</p>