
On Thursday, 14. July 2011 10:03:23 Mats Rauhala wrote:
Could you give an example how CPS helped your situation? I'm trying to grok continuation passing style, but for now it just seems to complicate and/or slow down code (stack)
Well it turned out my problem was entirely syntax. If had understood, that an ajax call basically looks like this: // make two successive ajax calls callAsync (remoteFunction1, ["arguments"], function(ret,exc) { //do something with ret and exc var x = ret[1] callAsync(remoteFunction2, [x], function(ret,exc) { // do something else }} You make a remote call and specify what shall happen when the call returns by providing an anonymous callback function. The callAsync itself immediately returns. My only problem was the ugly nesting when I want to place multiple ajax calls which need to be executed in a precise order as in the example above. I cannot simply make the first call and return to make the second call. I would have no idea where exceution would commence after the return. That chain of function calls builds its own little world and you never "return" from this world. This reminded me of haskell Monads which can also create their own little worlds, where e.g. state is passed around . This is why I asked here. But it turned out it had little to do with Monads. Still it is a functional issue. I believe the code above is already CPS, but very ugly. For some reason I hadn't seen, that there is no need to define the callbacks inline, but I might as well assign them to a variables. Then the above code looks like: callAsync (remoteFunction1, ["arguments"], callback1); var callback1 = function(ret,exc) { //do something with ret and exc var x = ret[1] callAsync(remoteFunction2, [x], callback2) } var callback2 = function(ret,exc) { // do something else } This is more gentle to my eyes. The only difficulty is that callback1 and callback2 need to be defined at the time callAsync is called. Usually this is the case. I could of course reverse the order, which would make things safer, but then control will flow bottom- up, whereas all the regular code executes top-down. -- Martin