title: Cypress.io make async request in custom login command
body: <p>I want to configure a custom <code>login</code> command in which I have to make a signIn call which returns a promise.</p>
  <p><code>commands.js</code>:</p>
  <pre><code>Cypress.Commands.add(&quot;login&quot;, () =&gt; {
    AuthLib.signIn(username, password).then((data) =&gt; {
      cy.setLocalStorage(&quot;accessToken&quot;, data.accessToken);
    });
  </code></pre>
  <p><code>AuthLib.signIn()</code> returns a promise.</p>
  <p>Then I want to use this command in an <code>before</code> block:</p>
  <pre><code>  before(() =&gt; {
      cy.login();
      cy.saveLocalStorage();
    });
  </code></pre>
  <p>I notice that the promise is not resolved.
  A 'hacky' fix would be to add <code>cy.wait(4000)</code> between <code>login()</code> and <code>saveLocalStorage()</code>.
  But that makes my test depend on the loading time of the auth server</p>
  <p>I found this 'related' issue: <a href="https://stackoverflow.com/questions/49980311/cypress-io-how-to-handle-async-code">Cypress.io How to handle async code</a> where <a href="https://www.npmjs.com/package/cypress-promise" rel="nofollow noreferrer">https://www.npmjs.com/package/cypress-promise</a> is referred. But this library cannot be used in <code>before</code> or <code>beforeEach</code></p>
  <p>How can I await the promise returned from <code>login()</code> / make sure the promise from <code>login()</code> is resolved before doing <code>cy.saveLocalStorage()</code>?</p>
  <p><strong>Update</strong></p>
  <p>I added the examples of what works and does not work in : <a href="https://stackoverflow.com/posts/64392412">https://github.com/Nxtra/Cypress-Amplify-Auth-Example/blob/main/cypress/support/commands.js</a></p>
  <p>A solution would be to start with <code>cy.then()</code>:</p>
  <pre><code>Cypress.Commands.add(&quot;login&quot;, () =&gt; {
    cy.then(() =&gt; AuthLib.signIn(username, password)).then((data) =&gt; {
      cy.setLocalStorage(&quot;accessToken&quot;, data.accessToken);
    });
  </code></pre>