0

我有以下操作来使用 node_redis 创建用户:

server.post('/create_user', function(req, res, next) {
  控制台.log(req.body);
  var body = req.body;
  client.hincrby('users', 'count', 1, function(err, id) {
    client.hmset('用户:'+id,
    '用户名',body.username,
    '密码', body.password,
    '电子邮件',body.email,函数(错误,写){
      client.hmget('user:'+id, 'username', 'email', function(err, read) {
        res.send({id: id, username: read[0], email: read[1]});
      });
    });
  });
})

我正在考虑在这里阅读有关可延迟和承诺的内容: http ://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/

如何使用 Deferrables 和 Promises 重写此代码,从而允许更清晰的异常处理以及更好的流程维护?

动作基本上是:

  1. 增加计数器获取ID
  2. 使用 ID 设置用户的 Redis 哈希
  3. 从 Redis 返回创建的用户
4

2 回答 2

3

With promises you could do:

var Promise = require("bluebird");
//assume client is a redisClient
Promise.promisifyAll(client);

server.post('/create_user', function(req, res, next) {
    console.log(req.body);
    var body = req.body;
    client.hincrbyAsync('users', 'count', 1).then(function(id){
        return client.hmsetAsync(
            'user:' + id,
            'username', body.username,
            'password', body.password,
            'email', body.email
        );
    }).then(function(write){
        return client.hmgetAsync('user:'+id, 'username', 'email');
    }).then(function(read) {
        res.send({id: id, username: read[0], email: read[1]});
    }).catch(function(err){
        res.writeHead(500);
        res.end();
        console.log(err);
    });
});

Not only will this perform better than waterfall, but if you have a synchronous exception, your process won't crash, instead even synchronous exceptions are turned into promise rejections. Although I am pretty sure the above code will not throw any such exceptions :-)

于 2013-10-11T22:05:10.183 回答
1

我已经成为异步库的粉丝。它的性能非常好,并且具有清理可读性的出色方法。

这是您的示例使用异步瀑布函数重写的样子。

瀑布的基本设置是:

async.waterfal([ 函数数组 ], finalFunction);

注意:瀑布方法期望回调函数总是有第一个参数是错误的。这样做的好处是,如果在任何步骤返回错误,它会直接进入带有错误的完成函数。

var async = require('async');

server.post('/create_user', function(req, res, next) {
  console.log(req.body);
  var body = req.body,
      userId;

  async.waterfall([
    function(cb) {
      // Incriment
      client.hincrby('users', 'count', 1, cb);
    },
    function(id, cb) {
      // Higher Scope a userId variable for access later.
      userId = id;
      // Set
      client.hmset('user:'+id, 
        'username', body.username, 
        'password', body.password, 
        'email', body.email, 
        cb);
    },
    function(write, cb) {
      // Get call.
      client.hmget('user:'+userId, 'username', 'email', cb);
    }
  ], function(err,read){
      if (err) {
        // If using express:
        res.render('500', { error: err });
        // else
        res.writeHead(500);
        res.end();
        console.log(err);
        return;
      }
      res.send({id: userId, username: read[0], email: read[1]});
  })
})
于 2013-10-11T15:56:34.623 回答