How do I implement a synchronous wrapper in JavsScript?
<p>I am using Googles Analytics api in Javascript.</p>

<p>They provide a method that gets the result of a list, once the execution is done it calls a callback method with the result.</p>

<p>Looks something like this: </p>

<pre><code>gapi.client.analytics.management.accounts.list().execute(handleAccounts);
</code></pre>

<p>...</p>

<pre><code>function handleAccounts(results) {
        if (!results.code) {
        if (results &amp;&amp; results.items &amp;&amp; results.items.length) {

// See this code below.

        } else {
            console.log('No accounts found for this user.')
        }
    } else {
        console.log('There was an error querying accounts: ' + results.message);
    }
}
</code></pre>

<p>Generally this is fantastic, however... I need a flattened list of all child items so I keep calling like this:</p>

<pre><code> $.each(results.items, function (index, value) {

gapi.client.analytics.management.webproperties.list({ 'accountId': value.Id}).execute(handleWebproperties);
// and so on..
            })
</code></pre>

<p>The problem being if at any level you have more than one item you end up with multiple asynchronous calls shooting off, and I won't know when they have all finished to get the final list.</p>

<p>Other than writing something to keep track of how many calls have been made then waiting for that total to come back.</p>

<p>How can I easily know when they have all completed?</p>

<p>Thanks.</p>

<p>In summary:</p>

<p>A user can have multiple accounts, accounts can have multiple properties and properties can have multiple profiles.</p>

<p>I need all the profiles for all the accounts of a user.</p>
