我有以下操作来使用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]}); }); }); }); })
我想在这里阅读关于可延迟和承诺的内容:http://blog.jcoglan.com/2011/03/11/Promissions-are-the-monad-of-asynchronous-programming/
如何用延迟和承诺重写代码,允许更干净的异常处理和更好的过程维护?
这些行动基本上是:
有了你能做的承诺:
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);
});
});
这不仅比瀑布执行得更好,而且如果您有一个同步异常,您的过程不会崩溃,相反,甚至同步异常都变成承诺拒绝。虽然我非常肯定上面的代码不会抛出任何这样的异常:-)