简体   繁体   English

用于解析NodeJS对象数组的递归函数

[英]Recursive function for parse array of objects in NodeJS

i have a NodeJS controller like this: 我有一个像这样的NodeJS控制器:

     var importOrders = function (req, res, next) {

    var orders = req.body;

    var processOrder = function (order) {
        if(i<orders.length-1){
            try {
                if (orders[i].Order.Company === "Mondial") {
                    parseMondial(db, orders[i].Order, processOrder(orders[i++]), log);
                }
            } catch (error) {
                next(error);
                log.error('orders', 'error Importing', error, order);
            }
        }
    };

    var i = 0;
    processOrder(orders[i]);
    res.send(orders.length);

};

Inside parseMondial i do lot of queries in mongoDB with promises but this queries its relationship between them. 在parseMondial内部,我在mongoDB中使用诺言进行了很多查询,但这查询了它们之间的关系。

This doesnt work because i need to finish process inside parseMondial for do the next object parse, but doesnt wait. 这不起作用,因为我需要在parseMondial内完成处理以进行下一个对象解析,但不要等待。 I dont have idea how can i do it this..Any help its wellcome. 我不知道我该怎么做。任何帮助它的结果。

I threw some javascript into a plunkr to emulate what it would be like. 我将一些javascript放到了plunkr中,以模拟其效果。 Just open up the console and run the code. 只需打开控制台并运行代码即可。 You should see it going through and returning the data of Mondial Orders. 您应该看到它正在执行并返回Mondial Orders的数据。

http://plnkr.co/edit/22qyZox6WJLsv5qS2n11?p=preview http://plnkr.co/edit/22qyZox6WJLsv5qS2n11?p=preview

var req = {};
//Emulate orders in req
req.body = [
    {Order: {Type: 'Mondo Cool', Company: 'Mondial'}},
    {Order: {Type: 'Moo', Company: 'Cow Guys'}},
    {Order: {Type: 'Woof', Company: 'Dog Guys'}},
    {Order: {Type: 'Mondo Bacon', Company: 'Mondial'}},
    {Order: {Type: 'Bawk Bawk', Company: 'Cat Guys'}},
    {Order: {Type: 'Mondo Cheese', Company: 'Mondial'}},
];

//Fill in a mock db
var db = 'mockDb';

//Import Orders
var importOrders = function(req, res, next){
    var orders = req.body;
    var processOrder = function () {
      if(i < orders.length){
          if(orders[i].Order.Company === "Mondial"){
            parseMondial(db, orders[i].Order, processOrder);
            i++;
          } else{
            i++;
            processOrder();
          }
      } else {
        //Mocks ending the loop and perform final res.send()
         console.log('res.send');
      }
    };
    var i = 0;
    processOrder();
};

//Emulates parseMondial and async request/queries
function parseMondial(db,order,callback,log){
  //Do something with order asyncrounously
  setTimeout(function(){
    console.log(order);
    console.log('Did a query and waited for the response ' + order.Company);
    callback();
  }, 1000);
}

//Mock making a req to importOrders
importOrders(req,null,null);  

Once the code in parseMondial completes, you can call the callback and if you need to you can pass data. parseMondial中的代码完成后,您可以调用回调,并且如果需要可以传递数据。 However, it may not have reference to i or orders within parseMondial, so to be safe, I handled passing the orders and iterating the index outside of parseMondial. 但是,它可能没有引用i或parseMondial中的命令,因此,为了安全起见,我处理了传递命令并在parseMondial之外迭代索引。

Passing in processOrders() isn't a callback. 传入processOrders()并非回调。 Passing processOrders provides it as a function that can be called at the end of parseMondial. 传递processOrders将其作为可在parseMondial末尾调用的函数提供。

I took out some of the try/catch stuff just to make the code simpler to read and use to your purposes. 我删除了一些try / catch东西,只是为了使代码更易于阅读和使用。

Finally i did this: 最后我做到了:

var importOrders = function (req, res, next) {

    var orders = req.body;
    var i = 0;

    var doNext = function () {
        i++;
        processOrder();
    };

    var processOrder = function () {
        if (i < orders.length) {
            try {
                if (orders[i].Order.Company === "Mondial") {
                    parseMondial(db, orders[i], doNext, log);
                }
            } catch (error) {
                next(error);
                log.error('orders', 'error Importing', error, orders[i].Order);
            }
        }else{
            res.send({total:i});
        }
    };
    processOrder();
};

And inside parseMondial, when i finish all the tasks i do calback(); 在parseMondial内部,当我完成所有任务时,我会执行calback();。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM