Trying to write #JavaScript without Promises? TL;DR Don’t! Using @cujojs when.js instead

danielskullIt’s weird, but I dodged a lot of the web development churn that happened in the late 90s, early 2000 era due to my involvement in thick client, closed source work. Basically, I never worked with JavaScript in the early days. And back then, when I would peek at the source of a website, the stuff I saw was cryptic and appeared unassailable.

Suffice it to say, in recent years, I have gotten real excited about JavaScript. For starters, I have enjoyed its function-oriented nature. If you can get past some of the really cryptic and hard to understand syntax decisions, and only adopt “the good parts”, it’s quite intriguing. I don’t think I could make it 100% my career, but learning more about JS has been quite interesting. And being dubbed “JavaScript Padawan” by some past colleagues was quite endearing.

But one thing I learned real fast was that JavaScript has some sneaky APIs. And by sneaky, I mean that here is async behavior at every turn. I was trying to fix a usage problem with my Spring Data REST demo app (shrink images way down before upload) when I found what clearly appeared to be an async issue. I thought I had found the answer, but Brian Cavalier quickly pointed out that my assumptions were mistaken, and spotted something I would never have realized.  “img.src = /*new image data*/” is an async operation.

Seeing that, I knew what to do. Wrap the subsequent operations in a when.promise, stuff the “return” statement inside a “resolve” operation, and THEN do the img.src assignment.

You see, the only way to really handle asynchronous operations is to embrace Promises, when.js is a killer library for that. It won’t drag in other stuff not needed like some of these universal toolkits. With a Promise-based approach, I have been able to easily build up my snap-a-pic-upload-to-the-server demonstration of Spring Data REST. It really makes things easy to read, and easy to maintain. The first rule about writing software is that you need to be able to come back six months later and understand what you wrote. By breaking up clearly async steps into tiny, chained promises, the results become obvious.

So if you are getting frustrated with JavaScript’s hidden async bits and pieces (after you start using === for equality checking), ask yourself, “Am I using Promises to manage this?”

Kaypro_in_Israel_1984

Leave a Reply

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