You can execute multiple redis commands in one call either through transaction or lua script. That way you won't have to deal with one callback per command, but rather execute multiple commands and deal only with one callback. For example try to look at multi method/command in redis client.
Dealing with asynchronous node_redis functions, awkward using INCR on two keys at once
-
30-05-2022 - |
Question
Say my server is preparing a new object to send out in response to a POST request:
var responseObj = {
UserID : "0", // default value
ItemID : "0", // default value
SomeData : foo
}
Now, when I create this new object, I want to increment the UserId
and ItemID
counters that I'm using in redis to track both items. But that seemingly requires two separate asynchronous callbacks, which seems like a problem to me, because I can't just stick the rest of my response-writing code into one of the callbacks.
What I mean is, if I only had one key and one callback to worry about, I would write something like:
app.post('/', function(req, res, next) {
// do some pre-processing
var responseObj = {};
redis.incr('UserID', function(err, id) {
responseObj.UserID = id;
// do more work, write some response headers, etc.
res.send(responseObj);
});
}
But what do I do with two INCR callbacks I need to make? I don't think this would be right, since everything is asynchronous and I can't guarantee my response would be correctly set...
app.post('/', function(req, res, next) {
// do some pre-processing
var responseObj = {};
redis.incr('UserID', function(err, id) {
responseObj.UserID = id;
// do some work
});
redis.incr('ItemID', function(err, id) {
responseObj.ItemID = id;
// do some work
});
res.send(responseObj); // This can't be right...
}
I feel like I'm missing something obvious, as a newbie node.js and redis programmer...
La solution