数据库怎么实现同步查询?
发布于 10 年前 作者 lzxue 5822 次浏览 最后一次编辑是 8 年前
 pusher.getUsers(function(err,da){

 var data=da;
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {


for(var i=0;i<data.length;i++)
{
    var col= db.collection('test');
      var id=data[i].id.toString();

    col.count({"FakeId":id}, function(err, count) {

          // return callback(count,)
         if(count==0)
         { console.log(count);
             pusher.getUserDetail(data[i].id,function(err,data){
                 console.log(data.id);
                 col.insert(data,function(err,result){
                     console.log(result);
                 });



             })

         }



    });


}
});

遍历Data数组,并判断data里面的数据是否存在数据库中,不存在的话插入数据库。col.count异步执行,(有没有办法同步执行)在异步函数里面使用data[i].id 里面的i不是对应是不对应的怎么解决?

4 回复

你看看async库,应该对你有用

其实你可以用闭包来“留住”i的值 (function(t){“for循环里面的代码放这里”})(i)

文章第五节,场景:对数据库的连续操作 http://blog.fens.me/nodejs-async/

async确实可以符合你的需求,不过对这样操作的性能表示怀疑。mongodb没有事物机制么,redis有的。

回到顶部