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:

  1. Create a new window
  2. Get data from the server
  3. Format the data with links
  4. 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.

Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: