Reputation: 676
I need to do several request to Redis db, and I need the response from a request to do the next one.
Let's analyze this example: (I'm using node_redis for the requests)
var message-id = undefined;
// request the next id
client.incr("message-id", function(err, id) {
message-id = id;
});
// use the 'next id' for storing a message
client.hmset("messages", message-id, messageContent);
This way doesn't work, because message-id id still undefined when I call client.hmdet()
.
The following is the lazy way, and it consist in put the client.hmdet()
inside the client.incr()
callback.
var message-id = undefined;
// request the next id
client.incr("message-id", function(err, id) {
message-id = id;
// use the 'next id' for storing a message
client.hmset("messages", message-id, messageContent, function(){
//more request here
});
});
I think this is not a good way to proceed, because if I have lots chained request, I need to put each request inside its previous request callback, and this will create a block of code hard to maintain.
I'm interested in the best practices for doing lots of request asynchronously. Can someone advise me?
Upvotes: 0
Views: 782
Reputation: 2754
I recommend you to have a look to the async module, it implements several patterns that you can use. your example async waterfall
async.waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
callback(null, 'three');
},
function(arg1, callback){
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
And also if you want to explore other possibilities beyond the callback pattern, you have the q module that implements promises A+
Upvotes: 1