Adventures in Javascript

Callback Hell, Express, and Koa

I would like to start off by saying that I love Node because it was enables me to write full-stack web applications built entirely in JavaScript. A lot of applications only use JavaScript for the front-end of the app because that is what it was originally intended for, but with Node we can build entire applications! Yay! *raucous applause*

However, using Node on its own can be tricky. When I was first learning how to set up my server-side using Node, my friend gave me this advice: “First lesson in using Node – use Express. ” I was curious about what he meant, but forged forward, only to soon find myself in callback hell with a series of other issues.

Callback Hell

Callback functions are functions that are executed at a later point in time. Because JavaScript allows for asynchronous behavior, Node uses callbacks a lot to help deal with this. Instead of having functions just return a value, they will wrap that result in a callback function. Since functions can’t execute until all the parameters are evaluated, the callback will only fire once the asynchronous job it needs to do is complete. Once you get used to callbacks they aren’t so bad, but your code can get complicated and hard to read if you don’t take steps to keep your code modular and clean. Callback hell happens when you end up having callbacks within callbacks within callbacks.

Additionally, when using Node on its own, you have to worry about parsing POST requests in a certain way. Frameworks have many different modules you can choose from to simplify this process.

Solution: Frameworks

Express

Express is a popular framework to use with Node. Honestly, once I started using Express I have never gone back to creating an app using just Node by itself – there are just too many benefits. Express makes routing, serving up your static files, and a host of other things super simple. For instance, you can require body-parser, a middleware that helps you take care of parsing data easily.

Koa

Koa differs from Express because it uses generator functions, a feature in ES6 that I happen to like a lot! Interestingly, the people who are behind Koa are the same people that made Express, and they set out to make a tool that would make creating the server side your app even easier. Anything you can do with Express you can do with Koa, but getting used to generator functions their syntax can take a little time.

Conclusion

I’m realizing as I’m writing this that this blog post should/could actually be turned into about three or four posts specifically introducing Express and Koa specifics.