I'm new to nodejs and maybe don't got an event system how it should work. Can't find a bug. Please advice. I need a simple task - check for a tag, if it does not exists, set the new key and info about the tag. The problem is - then I run the script for the first time, it's always returns 'keys not exists'. Check the redisdb keys - it creates many tags Here is my code
for (x = 0; x < rows.length; x++) {
if (rows[x].term_taxonomy_id != 1) {
var taxonomy = findOne(rterms, rows[x].term_taxonomy_id);
rc.exists('tag:' + taxonomy.name, function (err, rexists) {
if (rexists == false) {
rc.incr('tags:count', function (err, id) {
console.log(taxonomy.name+' not exists. result ' + rexists);
rc.set('tag:' + taxonomy.name,id);
rc.hmset('tag:' + id,
'id', id,
'title',taxonomy.name,
'url', taxonomy.slug
);
});//incr
}else{
console.log(taxonomy.name+' exists!'+rexists);
};
});//exists
};//ifrows
});
Here is another one example
var tags = [
"apple",
"tiger",
"mouse",
"apple",
"apple",
"apple",
"tiger",
"mouse",
"mouse",
];
var count =0;
Object.keys(tags).forEach (function (tag) {
rc.get("tag:"+tags[tag],function(err,rr){
console.log("get tag "+tags[tag]+" result code "+rr);
if (rr == null) {
rc.set("tag:"+tags[tag],"info",function(err,rr){
count++;
console.log('set tag '+tags[tag]+' '+rr+' objects count '+count);
});
};
});
})
the output:
get tag apple result code null
get tag tiger result code null
get tag mouse result code null
get tag apple result code null
get tag apple result code null
get tag apple result code null
get tag tiger result code null
get tag mouse result code null
get tag mouse result code null
set tag apple OK objects count 1
set tag tiger OK objects count 2
set tag mouse OK objects count 3
set tag apple OK objects count 4
set tag apple OK objects count 5
set tag apple OK objects count 6
set tag tiger OK objects count 7
set tag mouse OK objects count 8
set tag mouse OK objects count 9
Looks like nodejs executes all 'get' commands and only after that 'set' commands. So... I understand, it's all because of async operations. But how to make it work?