Last Updated: February 25, 2016
·
3.145K
· richthegeek

Writing conditional callbacks in a linear fashion in JS

Working in Node.JS makes it very easy to reach "callback hell" and whilst their are several ways to get around this the solutions often don't work in small/contained sections of code.

The main problem I face is when I have a condition altering how the next part of the program is executed by maybe adding a callback, something like:

callback = (err, data) ->
    the rest of my program

if some_clause is true
    mongo.find conditions, callback
else
    callback null, []

In this case, callback needs to be defined before (above) it is called, so the order of the method is no longer linear - instead it hits line 100 before jumping back to lines 50 through 99. This makes understanding the code a lot more difficult for me.

Lately, however, I've adopted the following approach:

if some_clause is true
    fn = (callback) -> mongo.find conditions, callback
else
    fn = (callback) -> callback null, []

fn (err, data) ->
    the rest of my program

This way, the program executes in-order and code comprehension is much improved (or at least, as much as it can with callbacks)

If you know an improvement on this technique do let me know!