Kein
Kein

Reputation: 996

Using node js and redis - get readable code

May be this is simple and stupid question, but im just learning my first asynchronous server language and redis is my first key-value db.

Example. I need do this:

$x = users:count
get user:$x

But with asynchronic javascript i get this code

redis-cli.get('users:count', function(err, repl){
  if(err){
    errorHandler(err);
  } else {
    redis-cli.get('user:'+repl, function(err, repl){
      if(err){
        errorHandler(err);
      } else {
        console.log('We get user '+repl+'!')
      }
    })
  }
})

This code not so large and not nested to much, but it's look like on my firt not example/test project i get crazy nested functions-callbacks.

How solve this and make pretty and readable code?

Upvotes: 0

Views: 554

Answers (1)

Raynos
Raynos

Reputation: 169421

function getUserCount(callback, err, repl) {
  if (err) {
    return callback(err);
  }
  redis-cli.get('user:' + repl, getUser.bind(null, callback));
}

function getUser(callback, err, repl) {
  if (err) {
    return callback(err);
  }
  console.log('We get user ' + repl + '!');
}

redis-cli.get('users:count', getUserCount.bind(null, errorHandler));

bind works wonders. If you prefer to have the bind abstracted then you can use this to store state that would normally be stored in closures like:

require("underscore").bindAll({
  run: function (errorHandler) {
    this.errorHandler = errorHandler;
    redis-cli.get('users:count', this.getUserCount);
  },
  getUserCount: function (err, repl) {
    if (err) return this.errorHandler(err);
    redis-cli.get('user:' + repl, this.getUser);
  },
  getUser: function (err, repl) {
    if (err) return this.errorHandler(err);
    console.log('got user ', repl);
  }
}).run(errorHandler);

Upvotes: 2

Related Questions