我是新手,对于nodejs的事件系统不太熟悉。无法找到错误,请给予建议。 我需要完成一个简单的任务 - 检查标签是否存在,如果不存在,则设置新的键和标签信息。 问题是-当我第一次运行脚本时,它总是返回“键不存在”。检查redisdb键 - 它创建了许多标签。 以下是我的代码:
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
});
以下是另一个示例
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);
});
};
});
})
输出结果:
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
看起来nodejs执行所有'get'命令,然后才执行'set'命令。所以……我理解,这都是因为异步操作的缘故。但是如何让它正常工作呢?