我是 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'命令之后。所以......我明白,这都是因为异步操作。但是如何让它发挥作用呢?