Recently, I’ve been working on the ZuiPrezi client side backend and there are loads of asynchronous requests for resources, which are, to be precise, a pain in the arse.
For instance, if I need “Arial” and then “Verdana” and then a presentation in this order, I would write something like this:
1 2 3 4 5 6 7 8 | backend.getFont("arial", function(data:Font):void { backend.getFont("verdana", function(data:Font):void { backend.loadPresentation(12) }) }) |
Pseudo solution
The way I would describe it in pseudocode could be like this:
1 2 3 4 5 | getFont("arial") then getFont("verdana") then getPresentation(12) |
AS3 solution
Let’s make it more AS3 like:
1 2 3 4 | new Chain( { arg: "arial", command: getFont }, { arg: "verdana", command: getFont }, { arg: 12, command: getPresentation } ); |
Although it works, I don’t like the syntax very much. We can make it better.
1 2 3 4 5 | (new Chain() .execute("arial", loadFont) .execute("verdana", loadFont) .execute(12, getPresentation) ); |
Parallelism
One more thing, does it support parallelism, It does.
1 2 3 4 5 6 7 8 9 10 11 12 | (new Chain() .begin .execute("arial", loadFont) .execute("verdana", loadFont) .execute(12, getPresentation) .end .begin .execute("helvetica", loadFont) .execute("futura", loadFont) .execute(1, getPresentation) .end ); |
Here you can download the sourecode.
Finally, If I want to sum up how it works, here is an overall figure:
Everything within begin - end happens synchronously, one by one,
and every begin - end pair runs simultaneously.
What do you think?
Finally, there is an interesting article by John Resig about Chaining with JQuery.
No Comments