javascript - Node.js 和 Express : Sequential execution flow one mongodb query request after another

标签 javascript node.js mongodb express

我有一个在 node.js 和 Express 中运行的网络服务器,它从 mongodb 检索数据。在 mongodb 中,集合是动态创建的,新创建的集合的名称将存储在一个元数据集合“project”中。我的要求是首先迭代元数据集合以获取集合名称,然后进入每个集合以根据某些条件执行多个查询。因为我的集合元数据是动态的,所以我尝试使用 for 循环。 但它提供了错误的数据。它没有执行sequent。在完成循环执行之前,它返回值。如何仅使用 Node 核心模块在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
            });

        });
    });
};

最佳答案

当您想要按顺序调用多个异步函数时,您应该调用第一个函数,在其回调中调用下一个函数,依此类推。代码如下所示:

asyncFunction1(args, function () {
  asyncFunction2(args, function () {
    asyncFunction3(args, function () {
      // ...
    })
  })
});

使用这种方法,您可能会得到一段难看且难以维护的代码。

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

<小时/>

以下是使用 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);
<小时/>

For循环模拟示例:

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);

关于javascript - Node.js 和 Express : Sequential execution flow one mongodb query request after another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175271/

相关文章:

MongoDB 文本索引多词搜索太慢

javascript - Svelte:将 noscroll 类名从组件添加到正文

javascript - ag-grid 中的 selectionChanged 事件

javascript - 如何使用 React hooks 和 Redux 从 useEffect 执行 store.unsubscribe

node.js - express.js 实例化 Controller 中出现意外值 'this'

node.js - MongoDB/Mongoose - 按日期查询对象数组

javascript - HTML 和 CSS 更改整个网页上的日期格式

node.js - BigQuery/Node.js 时间戳偏离

javascript - 使用 Promises 处理来自 ssh2 的成功/错误响应

MongoDB 文本搜索和多个搜索词