Marcus Node Bits: Callback function is cool stuff, and I even know how to write them

Posted by Marcus Hammarberg on February 6, 2014
Stats
I'm writing down some of the things I've picked up when I started to learn about NodeExpress and Mongo. Here are all the post in the series:
This is not Node related but rather a Javascript thing that was something that I had a real hard time with at first. And I know that I should learn about promises, but I haven't yet.
I'm writing down some of the things I've picked up when I started to learn about NodeExpress and Mongo. Here are all the post in the series:
This is not Node related but rather a Javascript thing that was something that I had a real hard time with at first. And I know that I should learn about promises, but I haven't yet.
Functions are first class citizens in Javascript, which is super cool and something that you'll make use of A LOT. Passing functions to functions is just the way to go in Node code. One thing that this manifests itself is through the concept of "callbacks".

Callbacks is pretty easy on the concept level; a function does something and then "call back" to the caller when the work is done. The callback is simply a function that you pass to the function as a parameter. Like this function:

Quite simply (eh ... not really the first time I saw this but anyway) doSomething will execute using 123 as the p parameter. It will finally call the callback function and hence execute my little anonymous function that does the console.log.

It took some time to wrap my head around this. And Yes, I know that promises is the new kid on the block, but I haven't come there yet.

The first time it really clicked for me was actually when I started to write my code in another way. It was since I messed up the parentheses, curlys and semicolons a lot. So I write (most often) my function calls in this sequence, which helped me realise that the function is just another parameter. It also saved me from a lot of JSLint errors.

After awhile this way of writing will get boring and tedious so I will stop. Right now it helps me understand the structure so I'll keep doing this.

Just to be clear, I love JSLint and it makes me look like I know how to write proper, well-formatted Javascript, when I actually don't :) There's an excellent plugin to Sublime. Get it now


Published by Marcus Hammarberg on Last updated