Nodejs mongodb本机驱动程序,异步请求的执行顺序

时间:2012-09-03 16:56:35

标签: node.js mongodb

有没有人有一个很好的方式来订购mongodb请求,因为Nodejs是异步的。

假设我将data1插入数据库,并且我立即请求读取该数据,我的读取请求可能会在数据写入数据库之前执行。

有没有一个很好的方法来代替强制请求的同步行为?

1 个答案:

答案 0 :(得分:2)

您可以简单地使用仅在完成插入后才会调用的回调。

var
    mongodb = require('mongodb'),
    client = new mongodb.Db('test', new mongodb.Server('127.0.0.1', 27017, {})),
    test = function (err, collection) {
        collection.insert({ hello : 'world' }, {safe:true}, function(err, docs) {
            collection.count(function(err, count) {
                console.log(count);
            });

            collection.find({ hello : 'world' }).toArray(function(err, results) {
                console.log(results);
            });
        });
    };

client.open(function(err, client) {
    client.collection('test_collection', test);
});

如果您需要更复杂的功能,请查看async模块。它应该可以帮助您组织许多回调。

相关问题