2013-10-11 38 views
0

我有以下操作来创建与node_redis用户:如何使用可延迟来执行一系列Redis操作?

 
server.post('/create_user', function(req, res, next) { 
    console.log(req.body); 
    var body = req.body; 
    client.hincrby('users', 'count', 1, function(err, id) { 
    client.hmset('user:'+id, 
    'username', body.username, 
    'password', body.password, 
    'email', body.email, function(err, write) { 
     client.hmget('user:'+id, 'username', 'email', function(err, read) { 
     res.send({id: id, username: read[0], email: read[1]}); 
     }); 
    }); 
    }); 
}) 

我想阅读有关可延迟和Promisses这里:http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/

如何验证码与Deferrables和Promisses改写,使清洁例外处理和更好的过程维护?

的行动基本上是:

  1. 增加计数器拿到ID
  2. 的用户设置Redis的哈希ID为
  3. 返回从创建的Redis

回答

3

有了承诺,你可以这样做:

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

这不仅表现比瀑布更好,但如果你有一个同步异常,你的进程不会崩溃,反而甚至同步 例外变成承诺拒绝。虽然我很确定上面的代码不会抛出任何这样的例外:-)

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]}); 
    }) 
}) 
+0

谢谢!正是我正在寻找的! – poseid