Personal Website For My Work

Chain of responsibility for ajax callback hell…

The app instance editor mentioned in the post.
(Click for full-size screen shot)

So I found myself in callback hell because I’m writing 3-4 web services at once and 2 of them work in tandem. nxWares and nxLogin. nxLogin is the OAuth2 authorization server and nxWares is the app instance management web service. It completely manages the identity of a given app instance: users, client id, client secret, configuration, etc. Because of this there is data that I don’t want to save locally as saving it and tracking external state would be too much of a nightmare at this stage, so I created something of a chain of responsibility pattern in the form of a function queue. The code is at the bottom in excerpts and commented.

I’ve got a ways to go…but it’s working out nicely. You basically create an object that holds parameters that any of the functions in the chain may need access to or co-operate on and create an array of functions, pushing on the functions in the order they need to execute. When each executes, it can pull the parameter it needs from the params object, operate on it, update it if it is a co-operative parameter, and then call nextFunc(params, funcs) before it exits, which passes the potentially updated params to the next function in the queue along with the array of functions.

nextFunc() pulls the next function from the queue, removing it from the front of the array, and executes it. Interestingly, since the functions in the chain co-operate, if something errorneous happens that would interfere with the objective, it can display an error and break the chain by not calling nextFunc(). Additionally, if a function in the chain has something it needs to happen after the objective is complete, it can push a function for it into the function queue and if there are no errors it will be called at the end.

Source Code Excerpts



	
Categories: Development

One comment on "Chain of responsibility for ajax callback hell…"

  • Its like you read my thoughts! You seem to grasp a lot approximately this,
    such as you wrote the book in it or something.

    I believe that you simply can do with a few percent to force the message home a little bit,
    but other than that, that is excellent blog.
    An excellent read. I will definitely be back.

Leave a Reply

Your email address will not be published. Required fields are marked *