Serialize redis data with node
Problem
I am using Redis and node (with node_redis) and I would like to serialize data from redis into an XML file (using simple-xml-writer), but I stumble upon the asynchronous behavior of node.
I have datasets for a,b,c,d and e stored as a hash in redis, the keys are data:a, data:b data:c ... and each key accesses a hash. Now my XML file should look like this:
(data for a)
(data for b)
...
My approach is to do something like:
myobjects = Array.new();
["a","b","c","d","e"].forEach(function(str) {
database.hmget("data:" + str,function(err,obj){ myobjects.push(obj) });
});
now_serialize_myobjects();
Is it possible to wait for the forEach
-loop to finish and be sure all objects in database.hmget()
are stored? So when calling the function now_serialize_myobjects()
, all objects covered?
What is the best approach to that problem?
Solution
Simplest approach
myobjects = Array.new();
var something = ["a","b","c","d","e"];
something.forEach(function(str) {
database.hmget("data:" + str,function(err,obj){
myobjects.push(obj);
if(myobjects.length === something.length){
now_serialize_myobjects();
}
});
});
But why not serialize as requests return?
startxmlfile();
var something = ["a","b","c","d","e"];
var completionCounter = 0;
something.forEach(function(str) {
database.hmget("data:" + str,function(err,obj){
completionCounter++;
if (!err)
serialize(obj);
if (completionCounter ===something.length)
finalizexmlfile();
});
});
if you are loading a ton of stuff second one is better I think
Discussion
View additional discussion.