gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:05:14 26 4
gpt4 key购买 nike

我有以下操作来使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com