Wrapping my head around Asynchronous Javascript
Most of the Javascript I use involves AJAX. Even before I really knew how to program in Javascript , my first cut & paste programs were AJAX simply because of the site I’m building. As I get deeper into the coding, trying to get multiple parts of my site to work together, the asyncronous model is getting harder and harder to work with.
Here is a simple pseudo-code example:
myFunction = function () {
successHandler = function () {
}
failureHandler = function () {
}
ajaxSetup = function () {
}
ajaxSetup();
}
That’s not too bad. As I’ve said before, I think it’s a bit verbose, but workable.
Putting it into the regular flow of code is harder. Here is my (made up) example:
- Create a new window
- Get data from the server
- Format the data with links
- Update a counter on the server
In pesudo-code again, it might look like this:
createMyWindow();
myFunction = function () {
successHandler = function () {
formatTheData();
myCounterUpdate = function () {
myCounterUpdateSuccessHandler = function () {
}
myCounterUpdateFailureHandler = function () {
}
myCounterUpdateajaxSetup = function () {
}
myCounterUpdateajaxSetup();
}
}
failureHandler = function () {
}
ajaxSetup = function () {
}
ajaxSetup();
}
Yuck! I actually have some code like this and was just going to deal with it. But, one of my flows required a third layer.
I simply can’t maintain any sense of the program with so many layers! So, I went looking for solutions and found this blog post by Harry Fuecks. It’s a couple of years old, but seems to capture exactly what my issue is and has some solutions. One is called Narrative Javascript and another is jwacs.
I’m not sure I like any of the solutions, though, since they involve adding a lot more code. But, I’m still wrestling with this issue, trying to re-factor a bit to gain control and see what other solutions there might be.
No comments yet
Leave a reply