2

I am coming from a PHP background and am now trying to get used to the event driven paradigm of Node.js. However, my code quickly get messy. Below I compare procedural code with actual Node.js Redis code. Am I doing this right?

PROCEDURAL (pseude code)

if(!client.get("user:name:koen")) {
    client.set("user:name:koen", "user:id:" + client.incr("count:users"));
}

EVENT DRIVEN (actual code)

client.get("user:name:koen", function(err, res) {
  if(!res){
    client.incr("count:users", function(err, count){ 
      client.set("user:name:koen", "user:id:" + count, function (err, res) {
        callback(err, res);
      });
    }); 
  }
});
koen
  • 1,037
  • 3
  • 19
  • 27
  • Have a look at the Deferred concept of jQuery or similar libraries. It makes the code much more readable in my opinion. – Sirko Oct 27 '13 at 10:49
  • 1
    You mean "synchronous vs asynchronous". Both are procedural. As for the main issue: yeah, this is how you do it in asynchronous paradigm. You can use some helpers (like [async.js](https://github.com/caolan/async)) but in the end it will look more or less like this. – freakish Oct 27 '13 at 10:50
  • Alright, that's all I needed to know. Just wanted to make sure I wasn't over complicating things. Thanks. – koen Oct 27 '13 at 10:52
  • 1
    It's often referred to as [*callback hell*](http://stackoverflow.com/questions/18095107/callback-hell-in-nodejs). – Jonathan Lonowski Oct 27 '13 at 12:46

1 Answers1

1

Callback hell, mentioned in the question, is greately explained here, as well as how to write the code to avoid it:

http://callbackhell.com/

Andrzej Karpuszonak
  • 8,896
  • 2
  • 38
  • 50