title: Wait until function is finished using $.when
body: <p>I am trying to convert my page to PDF. </p>
  
  <p>I have two pages that are converted into base64 encoded image then added into a PDF using jsPDF. It works fine. </p>
  
  <p>My problem is I want the code below wait for the domtoimage function to be treated before saving it. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var doc = new jsPDF();
  
  //First
  domtoimage.toPng(document.getElementById('page'))
  .then(function (dataUrl) {
             doc.addImage(dataUrl, 'png', 15, 10, 180, 280);
             doc.addPage();
  });
  //Second
  domtoimage.toPng(document.getElementById('page2'))
  .then(function (dataUrl) {
              doc.addImage(dataUrl, 'png', 15, 10, 180, 280);    });
  //Third
  doc.save("file.pdf");</code></pre>
  </div>
  </div>
  </p>
  
  <p>I found this solution: <a href="https://api.jquery.com/jquery.when/" rel="nofollow noreferrer">https://api.jquery.com/jquery.when/</a> but as I am not familiar with promise I don't know how to make it work.</p>
  
  <p>Thank you for your help.</p>