title: How to wait for a JavaScript Promise to resolve before resuming function?
body: <p>I'm doing some unit testing. The test framework loads a page into an iFrame and then runs assertions against that page.  Before each test begins, I create a <code>Promise</code> which sets the iFrame's <code>onload</code> event to call <code>resolve()</code>, sets the iFrame's <code>src</code>, and returns the promise.</p>
  
  <p>So, I can just call <code>loadUrl(url).then(myFunc)</code>, and it will wait for the page to load before executing whatever <code>myFunc</code> is.</p>
  
  <p>I use this sort of pattern all over the place in my tests (not just for loading URLs), primarily in order to allow changes to the DOM to happen (e.g. mimick clicking a button, and wait for divs to hide and show).</p>
  
  <p>The downside to this design is that I'm constantly writing anonymous functions with a few lines of code in them.  Further, while I have a work-around (QUnit's <code>assert.async()</code>), the test function that defines the promises completes before the promise is run.</p>
  
  <p>I'm wondering if there is any way to get a value from a <code>Promise</code> or wait (block/sleep) until it has resolved, similar to .NET's <code>IAsyncResult.WaitHandle.WaitOne()</code>.  I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.</p>
  
  <p>In essence, is there a way to get the following to spit out results in the correct order?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function kickOff() {
    return new Promise(function(resolve, reject) {
      $("#output").append("start");
      
      setTimeout(function() {
        resolve();
      }, 1000);
    }).then(function() {
      $("#output").append(" middle");
      return " end";
    });
  };
  
  function getResultFrom(promise) {
    // todo
    return " end";
  }
  
  var promise = kickOff();
  var result = getResultFrom(promise);
  $("#output").append(result);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div id="output"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>