com
com

Reputation: 2704

node.js redis smembers synchronously

I wonder if it's possible to implement synchronous retrieval of smembers of redis with node_redis.

_.each(seeds, function(subseed, key, list){

    client.smembers(subseed, function (err, replies) {
        retrieved = retrieved.concat(replies)
    })
})
client.quit();
console.log("start")
console.log(retrieved.length)

OUTPUT:

start
0
10

So it looks like I need somehow to get to the point when smembers finishes it's run, ot alternatively to run smembers in synchronous mode.

How can I solve this problem?

Upvotes: 4

Views: 6899

Answers (1)

yangsibai
yangsibai

Reputation: 1727

Why do you want to make it synchronous? If you want to do something after members, just do it in callback function.

var callback=function(res){
    retrived=retrieved.concat(res);
    //continue do other things
};

client.smembers("offer", function (err, replies) {
    if(!err){
        callback(replies);
    }
})

If you want to do something after a loop,you can try _.after of underscore.js,for example:

var times=10;

var arrayOfReplies=[]; //store all replies
var callback=function(){
    //do something with arrayOfReplies
}

var afterAll = _.after(times,callback); //afterAll's callback is a function which will be run after be called 10 times

for(var i=0;i<10;i++){   
    client.smembers("offer", function (err, replies) {
        if(!err){
            arrayOfReplies=arrayOfReplies.concat(replies);
            afterAll();
        }
    })
}

see more:http://underscorejs.org/#after

Upvotes: 8

Related Questions