getting rid of nesting required for javascript callbacks
<p>I've got some javascript functions that take perform asynchronous requests over the network and take a callback to "return" data via.  Here is an example of what this looks like when I use it:</p>

<pre><code>RemoteQuery(server,query,function(ret) {
  // do something with ret
})
</code></pre>

<p>The problem is, if I have several queries in a row the code become quite nested and difficult to manage.  Since I am relying on scoped variables, I can't rip out each of these functions into a separate top-level function either.  Here is a toy example:</p>

<pre><code>RemoteQuery(server,query1,function(ret) {
      var x = ret[5]
      RemoteQuery(server,query2,function(ret) {
          var y = ret[3]
          if (x + y &gt; 10) {
              RemoteQuery(server,query2,function(ret) {
                  // do more stuff
              })
          }      
      })
})
</code></pre>

<p>Obviously if I have more than 2 or 3 queries it starts getting ugly, and I might have a lot more than that!</p>

<p>Ideally, I would like to represent the above without all that nesting, e.g.</p>

<pre><code>ret = RemoteQuery(server,query1)
var x = ret[5]
ret = RemoteQuery(server,query2)
var y = ret[3]
if (x + y &gt; 10) {
    ret =RemoteQuery(server,query2)
    // do more stuff
}
</code></pre>

<p>but the only thing I have thought of that might work would be to parse the javascript, recognize functions which have callbacks, re-write them in the correct form, and eval, but this seems awfully complicated and would make debugging very difficult.</p>

<p>Is there a better mechanism to do this?</p>
