Javascript非阻塞

时间:2013-10-30 11:52:40

标签: javascript node.js asynchronous

我的要求是首先打开db数据库,然后执行第二种方法。我尝试过我没有在JS中做过类似的事情,所以非常感谢任何建议/指导。

我的代码可以找到here。我怎样才能使这个异步?我可以选择setTimeout,我找不到好的做法......

任何例子都会非常有用。

1 个答案:

答案 0 :(得分:0)

此代码来自此https://github.com/mongodb/node-mongodb-native自述文件

  var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;    

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('test_insert');
    collection.insert({a:2}, function(err, docs) {

      collection.count(function(err, count) {
        console.log(format("count = %s", count));
      });

      // Locate all the entries using find
      collection.find().toArray(function(err, results) {
        console.dir(results);
        // Let's close the db
        db.close();
      });      
    });
  })
相关问题