0

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?

1
  • you'r missing a closing ) in line 6 of the first code block Commented Dec 6, 2013 at 11:19

1 Answer 1

1

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+

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Q module is really interesting!
Anyway, I think that could be really useful if any redis method has a flag for set the request as sync ora async... ;)
I really don't understand how to do this with promises A+ way... I't not explained well in my opinion... -_-'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.