我有以下操作来使用 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 基本上是:
- 增加计数器获取ID
- 设置用户ID的Redis hash
- 从 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/