javascript - 如何使用 deferrable 执行一系列 Redis 操作?

标签 javascript node.js redis promise

我有以下操作来使用 node_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]});
      });
    });
  });
})

我想在这里阅读有关 Deferrable 和 Promise 的内容:http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/

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

Action 基本上是:

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

最佳答案

有了你可以做的 promise :

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

这不仅比 waterfall 执行得更好,而且如果你有一个同步异常,你的进程不会崩溃,甚至是同步的 异常(exception)变成 promise 拒绝。虽然我很确定上面的代码不会抛出任何这样的异常:-)

关于javascript - 如何使用 deferrable 执行一系列 Redis 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19321905/

相关文章:

javascript - 试图理解这个 .contain() 函数的语法

node.js - PayPal 客户端验证失败

node.js - nodejs Kue作业处理逻辑

hash - 大量数据的键值对与哈希值

docker - Telegraf 在本地主机上的 Docker 容器上运行时如何监控 Grafana 上的 Redis 指标?

Javascript:在添加 CSS 样式的同时遍历数组

javascript - JSF 数据表分页中的当前页码

javascript - Angular JS 添加新行默认处于可编辑模式

javascript - 为什么我无法导出此表

node.js - 在 Node JS 中引用具有相同局部作用域变量名称的全局作用域变量