title: How do I wrap executions of asynchronous (callback-based) functions into a synchronous function in Javascript?
body: <p>I'm trying to write a function in Javascript (with jQuery, if you want):</p>
  
  <pre><code>function fetchItem(itemId) { return /* ??? */; }
  </code></pre>
  
  <p>This function relies on a second, predefined and unmodifyable function that looks like this:</p>
  
  <pre><code>function load(callback) { /* ... */ }
  </code></pre>
  
  <p>This function is asynchronous. After calling it, it fetches n items via XHR, then when they have arrived, stores them in the DOM, then invokes the callback.</p>
  
  <p><code>fetchItem</code> uses a simple jQuery selector (irrelevant here) to check the DOM for the element with <code>itemId</code> and calls <code>load</code> if the item isn't there yet. Rinse and repeat.</p>
  
  <p>My problem is that I want to wrap multiple asynchronous calls of <code>load</code> into my synchronous <code>fetchItem</code> function, which should return the DOM element with <code>itemId</code> after it has made enough <code>load</code> calls.</p>
  
  <p>Pseudo code, if <code>load</code> was synchronous:</p>
  
  <pre><code>function fetchItem(itemId):
      while not dom.contains(itemId):
          load()
      return dom.find(itemId)
  </code></pre>
  
  <p>My first attempts at doing this in Javascript, which probably display a lot of misconceptions about Javascript's closures and execution model: ;)</p>
  
  <pre><code>function fetchItem(itemId) {
      var match = undefined;
  
      function finder() {
          match = $(...).get(0);
          if(!match) {
              load(finder);
          }
      }
      finder();
  
      return match;
  }
  </code></pre>
  
  <p>Obviously, this fails because the <code>return</code> is executed before the first callback. Also, as you can see I had some problems getting <code>match</code> back out to <code>fetchItem</code>. Is it properly protected by the closure here? Would this work if fetchItem was executed multiple times in parallel, assuming that <code>load</code> supports this (and doesn't mix up the DOM)?</p>
  
  <p>I'm probably missing a perfectly good pattern here, but I don't really know what to google for...</p>