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?

Problem courtesy of: Kein

Solution

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);

Solution courtesy of: Raynos

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Using node js and redis – get readable code

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录