node.js和express:顺序执行流程一个接一个mongodb查询请求

Sum*_*eet 0 javascript mongodb node.js express

我有一个在node.js和Express中运行的web服务器,它从mongodb中检索数据.在mongodb中,集合是动态创建的,新创建的集合的名称将存储在一个元数据集合"项目"中.我的要求是首先迭代到元数据集合以获取集合名称,然后进入每个集合内部以根据某些条件进行多个查询.因为我的集合元数据是动态的,所以我尝试使用for循环.但它提供了错误的数据.它没有执行后续行动.在完成循环执行之前,它返回值.如何仅使用节点核心模块在node.js中执行顺序执行(不是其他库,如async ..);

exports.projectCount = function (req, res) {
    var mongo = require("mongodb"),
        Server = mongo.Server,
        Db = mongo.Db;

    var server = new Server("localhost", 27017, {
        auto_reconnect: true
    });

    var db = new Db("test", server);
   // global JSON object to store manipulated data 
    var projectDetail = {
        projectCount: 0,
        projectPercent: 0
    };
    var totalProject = 0;
    db.open(function (err, collection) {
        //metadata collection 
        collection = db.collection("project");
        collection.find().toArray(function (err, result) {
            // Length of metadata  collection 
            projectDetail.projectCount = result.length;
            var count = 0;
            //iterate through each of the array which is the name of collection 
            result.forEach(function (item) {
                //change collection  object  to new collection
                collection = db.collection(item.keyParameter.wbsName);
                // Perform first query based on some condition 
                collection.find({
                    $where: "this.status == 'Created'"
                }).toArray(function (err, result) {
                    // based on result of query one increment the value of count 
                    count += result.lenght;
                    // Perform second query based on some condition 
                    collection.find({
                        $where: "this.status=='Completed'"
                    }).toArray(function (err, result) {
                        count += result.length;
                    });
                });
            });
            // it is returning the value without finishing the above manipulation
            // not waiting for above callback and value of count is coming zero .
            res.render('index', {
                projectDetail: projectDetail.projectCount, 
                count: count
            });

        });
    });
};
Run Code Online (Sandbox Code Playgroud)

far*_*jad 9

当你想按顺序调用多个异步函数,你应该调用第一个,调用它的回调中的下一个,依此类推.代码看起来像:

asyncFunction1(args, function () {
  asyncFunction2(args, function () {
    asyncFunction3(args, function () {
      // ...
    })
  })
});
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您最终可能会遇到难以维护的丑陋代码.

有许多方法可以在不嵌套回调的情况下实现相同的功能,例如使用async.jsnode-fiber.


以下是使用node.js 执行此操作的方法EventEmitter:

var events = require('events');
var EventEmitter = events.EventEmitter;

var flowController = new EventEmitter();

flowController.on('start', function (start_args) {
  asyncFunction1(args, function () {
    flowController.emit('2', next_function_args);
  });
});

flowController.on('2', function (args_coming_from_1) {
  asyncFunction2(args, function () {
    flowController.emit('3', next_function_args);
  });
});

flowController.on('3', function (args_coming_from_2) {
  asyncFunction3(args, function () {
    // ...
  });
});

flowController.emit('start', start_args);
Run Code Online (Sandbox Code Playgroud)

对于循环仿真示例:

var events = require('events');
var EventEmitter = events.EventEmitter;

var flowController = new EventEmitter();

var items = ['1', '2', '3'];

flowController.on('doWork', function (i) {
  if (i >= items.length) {
    flowController.emit('finished');
    return;
  }

  asyncFunction(item[i], function () {
    flowController.emit('doWork', i + 1);
  });

});

flowController.on('finished', function () {
  console.log('finished');
});

flowController.emit('doWork', 0);
Run Code Online (Sandbox Code Playgroud)