title: Wait for function to execute before unloading javascript
body: <p>I have a piece of code which i wish to run before the browser refreshes or redirects</p>
  <pre><code>        window.addEventListener(&quot;beforeunload&quot;, async (event) =&gt; {
          await this.save()
      });
  </code></pre>
  <p>the method i'm running involves parsing JSON , updating it , and saving it back to the sessionStorage.Is there a way to make sure this.save() completes before unloading? or at least have it run in the background while the page redirects.</p>
  <p>I have tried removing the <code>async</code> and <code>await</code> code, but does not work.</p>
  <p>EDIT here is the save method:</p>
  <pre><code> saveCanvas = async (call_back_) =&gt; {
      const FlowState = JSON.parse(sessionStorage.getItem('FLOWSTATE'))
      ...
      ...
      await html2canvas(div).then((screenshot) =&gt; {
             ...
             ...
             sessionStorage.setItem('FLOWSTATE', JSON.stringify(FlowState))
          })
      } 
  }
  </code></pre>