Reputation: 91
I read a lot about this problem but I can't solve it. I'm working in a code in node.js and redis to get the data from a key. Of course, when I execute client.get it prints data as nul or undefined because of async. But I don't know how to solve it.
Example code: this part works fine
pubsub.on('psubscribe', function() {
while(i<end){
client.set( i , url, function() {
});
client.expire( i , 10);
console.log("New key: " + i);
i++;
}
});
Then, when the key expires I want to get de data to set it again in Redis:
pubsub.on('pmessage', function(channel, message) {
var keyData;
client.get(message, function(err,data){
keyData = data;
});
client.set( message , keyData, function(){});
client.expire( message , 10);
});
Of course, data is null.
How can I solve it?
Thanks a lot.
Upvotes: 0
Views: 8134
Reputation: 3617
The issue is because node is async in nature. Here is something that might help you out.
client.get(message,(err,data)=>{
client.set( message , data,()=>{
client.expire( message , 10);
});
});
This being said, it is a bad implementation and would lead to callback hell
. A better implementation using promise would be
var clientGet = (message)=>{
return new Promise((fullfill,reject)=>{
client.get(message,(err,data)=>{
if(err)
reject(err);
else
fullfill([message,data]);
});
});
}
var clientSet = (dataFromGet)=>{
return new Promise((fullfill,reject)=>{
let message,data = dataFromGet;
client.set(message,data,()=>{
fullfill(message);
});
});
}
var clientExpire = (message)=>{
return new Promise((fullfill,reject)=>{
client.expire(message,10);
fullfill();
});
}
And you can call them using
clientGet(message)
.then(clientSet)
.then(clientExpire)
.then(()=>{
console.log("All operations were fine");
})
.catch((ex)=>{
console.err(ex.message);
});
As i wrote previously it would lead to callback hell
which is basically a lot of callbacks inside one another. As you can see from the first part of the code that there were two functions, they might increase and usually makes the code more difficult to manage and read.
Upvotes: 2