Javascript Allongé: a review

javascript_allongeJavascript Allongé by @raganwald is one of the more refreshing coding books I have read in a big while. Usually when I face a programming language book, I skip the beginner chapters (if I already know the language, of course) and go directly for the juicy ones, but with this one I tried to follow it from end to end because I read some comments on twitter telling that the way basics are explained, become a really solid base for the language, so I gave it a chance.

And they were right! This book is not the usual Learn the language in 24 hours or something like that. It’s actually a very sharp and deep reading about Javascript and function composition.

The way the author explains how to create really simple functions and use them to build more complex ones just blowed my mind. The resulting code is so clear and easy follow that is almost impossible to imagine a better way to express that functionality.

This book is a total recommendation if you deal with Javascript in your day-to-day. I bought a digital copy in Leanpub, but recently the author made it opensource, so you’re free to get a copy of it:

RaspberryPi shutdown button

Last Friday I got some spare time (finally!) and, with the help and tools of my friend Alfredo, we placed a button in the RaspberryPi case so, when I push it, a custom command its executed on the RaspberryPi, like for example, a clean system shutdown.

First lets start with some pictures of the final result:

Continue reading

Madrid – OpenSpace Persistencia

Persistencia ha sido el tema tratado en el OpenSpace que se ha realizado en las oficinas de tuenti. Hemos podido hablar sobre temas como NoSQL, ActiveRecord, BD basados en grafos, geoespaciales, … entre otros muchos. Ha habido mucho debate, con muchas opiniones, pero sobre todo muy buen ambiente.

Muy interesante la charla que ha dado la gente de tuenti sobre como gestionan la persistencia. Es de agradecer la claridad y transparencia con la que han participado.

Dar las gracias a @borillo por el esfuerzo en la organización del evento y a tuenti por ofrecer sus oficinas para el evento.

Os recomiendo que en cuanto tengáis la oportunidad, acudáis a un OpenSpace siempre resulta una actividad muy gratificante y en la que seguro aprenderás algo nuevo.

Javascript Promises Pattern in plain Javascript

In the previous post I gave a glimpse of the Javascript Promises Pattern (JPP). Now we are going to take a more in deep look into it and implement our (simplified) version of this pattern.

First of all, let’s see how the code I we defined works: we had three operations (to make the example simpler, they all share the same code, but this is not a requisite), each of them expecting a set of arguments which are processed by an asynchronous operation. The result of this asynchronous operation will be feed to the next operation, and so on until we achieve processResults function that will handle the final result. This is a refactored version of the code exposed in the previous post:

Every operation creates a promise object that will be returned as result of the invocation to the operation. Furthermore, this promise object is used to store the future value that will result from the asynchronous call. This value is stored in the promise object using the resolve method.

This line is were all the magic is done: we invoke the first operation, which returns a promise object, and over this object we are invoking the then method, passing a function as its argument, which will be invoked when the promise object is resolved. Then we repeat this invocation to the then method in order to chain more callbacks, each of them being invoked by successive promise resolve invocations.

This may appear simple, but it’s kind of tricky: we pretend to receive the results of every operation as argument of the following callback. That works ok for operation1, but promises objects from operations 2 and 3 still don’t exist so there is no way to attach those promises to its correspondent callback. In other words, invoking the then method of the promise object doesn’t actually invoke operation2 and operation3 (in fact, the parameters they need are still not available). What really happens is that they are chained into the operation1 promise object.

So how does JPP resolve this? Well, the trick can be discovered paying attention to the instantiation of the promise objects: we passed this as first argument, which in fact turns to be global object Window for promise1 and operation1 promise object for the promise2 and promise3 instantiations. That’s because resolve method invokes callbacks functions applying itself as the current scope. Maybe it’s easier to see in code:

Having this idea clear, we can try to develop our own implementation for this pattern. We already have defined the constructor function, let’s go for the then and resolve methods:

As we said, then just store the function to call when the resolve method is invoked. resolve then just pops the callback function to invoke, applying current promise object (this) as its scope, so when the next operation tries to create a new promise object, it gets the actual promise object instead of a new one, which turns to be the one used to define the chain of callbacks.

Well, better than to read code to understand it, is to play with it, so here you have a fiddle ready to go. It’s a litlle more complex implementation than the exposed here, because I defined a reject method, but the main idea stands.

I would love to hear feedback from you about the pattern itself or the implementation, so don’t hesitate to post comments!

Javascript Promises Pattern – 101

I am sure you have heard about the javascript Promises Pattern, but if you haven’t, here is a quick and simple definition: a promise or future is an object that represents a future result, not yet obtained or calculated (here you have a more complete definition). In fact, what is really nice about it is that allows you to define callbacks for async code in and more elegant and readable way.

But wait a moment, what’s the problem with the actual callbacks system? Well, they work, but they become a big mess when you try to chain two or more of them, resulting in a code looking like a pyramid. Let’ see an example.

Suppose you have several async operations: operation1, operation2 and operation3 and they must be execute in strict sequence, that is, operation 2 must wait for operation1 to finish and so on. The resulting code will look like something like this:

This code is, at least, hard to follow and thus to understand (and in my opinion quite ugly), but it has been the common way to deal with asynchronism in javascript… until now. Look how the same code would look like using Promise Pattern:

Here you can clearly see that there are three different operations, that don’t appear to be tight one to another. The chainability of the three functions is established in the last line of code, making it clear with a glimpse that every operations depends on the result of the previous one, and thus, they must be executed in strict order. This line is the key of the Promise Pattern and it works because every operation return a promise object. We’ll deep into this in further posts.

This code can be heavy refactored, but I prefer to keep it like this to make it easy to understand how promises work. Anyway, I think you will agree with me that this code is much elegant and easy to understand than the previous one.

So far, so good. In further posts I will show you how to easily implement this pattern in plain javascript, and we will deep into the tricks that promises use to make this code work. By the moment enjoy using the implementations provided by the main javascript libraries (much more powerfull than the one we will create) like jQuery’s deferreds (they are the same concept as promises).

See you in following posts!

Retrospectiva 2012

31 de Diciembre, otro año más. Y uno nuevo a punto de llegar.

En mi caso es fácil resumir 2012 en un par de palabras: cambio y aprendizaje. Ha sido un año en el que profesionalmente he tomado un cambio de dirección y del cual estoy realmente satisfecho, aunque en su momento fue una decisión díficil, sobre todo por el momento de crisis en el que nos encontramos. Y es que este cambio me ha hecho aprender. Mucho.

Ha sido el año en el que he descubierto el Agilismo como técnica de trabajo, y que me ha permitido conocer muchos otros puntos de vista, distintos y muchos de ellos muy interesantes. Y esto me ha permitido hacerme una auto-crítica (o retrospectiva) de la cual puedo sacar una idea muy clara: más cambio. Y es que, pesar de las técnicas que he podido descubrir y de las tecnologías que he podido aprender, solo he encontrado una constante: Nunca dejes de aprender, lo que hoy sabes, cambiará, y debes estar preparado. No le tengas miedo y abrázalo como un reto constante.

Esto es más cierto, si cabe, en la informática, ya que el cambio ocurre en plazos realmente cortos, y los cambios que avecinan parecen no ser pequeños. ¿Quién me iba a decir a mi en Enero de este año que terminaría habiendo hecho formaciones sobre Agilismo y Scala y que el hype tecnológico a finales de año se centraría en HTML5 y  Javascript? No way… pero así es, y la verdad es que es un mundo realmente emocionante el que nos espera este próximo año.

Aunque sin duda el cambio más importante que he experimentado este año no se puede definir en palabras:

Izan - 2012 / 10 / 11

Izan – 2012 / 10 / 11

¡Feliz año 2013!

Valencia – Global Day of Coderetreat 2012

Creo que la mejor forma de iniciar este post es felicitando a los organizadores (@borillo, @xaviuzz, hay que reconocer que os lo habéis currado) y dando las gracias a peerTransfer por hacer de host para este evento de forma totalmente altruista.

Una pena para aquellos que no hayan podido asistir: ha resultado ser un evento muy dinámico, con opiniones y puntos de vista muy variados e interesantes y, sobretodo, divertido.

El problema a resolver (Conway’s Game of Life), aunque simple en principio, ha dado mucho juego, y aunque un pomodoro no es suficiente para implementar una solución completa, ni mucho menos, ha sido la excusa perfecta para practicar pair programming, TDD y ya de paso, poner en práctica algún nuevo lenguaje y herramientas.

¿Qué más se puede esperar de un Sábado de programación por el mero placer de programar y aprender?

Y ahora a ver si consigo implementar una versión del juego medianamente completa, que al final me he quedado con las ganas. ¡Esto es puro vicio!

http://coderetreat.org/events/global-day-of-coderetreat-valencia-spain

Code, opinions and some other geek-stuff

Follow

Get every new post delivered to your Inbox

Join other followers: