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:
RemoteQuery(server,query,function(ret) {
// do something with ret
})
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:
RemoteQuery(server,query1,function(ret) {
var x = ret[5]
RemoteQuery(server,query2,function(ret) {
var y = ret[3]
if (x + y > 10) {
RemoteQuery(server,query2,function(ret) {
// do more stuff
})
}
})
})
Obviously if I have more than 2 or 3 queries it starts getting ugly, and I might have a lot more than that!
Ideally, I would like to represent the above without all that nesting, e.g.
ret = RemoteQuery(server,query1)
var x = ret[5]
ret = RemoteQuery(server,query2)
var y = ret[3]
if (x + y > 10) {
ret =RemoteQuery(server,query2)
// do more stuff
}
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.
Is there a better mechanism to do this?
The ‘proper’ way to do it is to write function declarations for them and avoid relying on the scoped variables (so pass them to each function). Something like:
Since you have to call those RemoteQuery(ies) asynchronously, there’s no way really to do the solution you suggest in your question. Use of the
Deferredobject may do the trick but I think you’d still have to restructure your functions (since you’re aiming to avoid the nestedness).