在node.js中使用异步模块嵌套For循环

时间:2016-10-11 14:13:32

标签: node.js asynchronous async.js

我正在尝试使用async模块执行嵌套for循环,以便处理nightmare回调函数的异步。简而言之,我正在做的是我在同一个nightmare实例中运行的node个对象很少,以便浏览网站上的不同链接。

根据我读过的内容,我必须调用next()函数才能通知asyncOfSeries循环继续下一个索引。只需一个for循环就可以正常工作。当我嵌套asyncOfSeries时,内部next()函数不在内循环上执行,只在外循环上执行。

请参阅代码片段,以便更好地理解:

 var Nightmare = require('nightmare');
 var nightmare = Nightmare({show:true})

var complexObject = {

 19:["11","12","13","14","15"],
 21:["16"],
 22:["17"],
 23:["18","19"]
};
//looping on each object property
async.eachOfSeries(complexObject, function(item, keyDo, next){
  //here im looping on each key of the object, which are arrays
  async.eachOfSeries(item, function(indexs, key, nexts){
    nightmare
    .//do something
    .then(function(body){

        nightmare
        .//do something
        .then(function(body2){

           nightmare
          .//do something
          .then(function(body3){

            //Here I call next() and expecting to call the next index of the inner loop
            //but is calling the next index of the outer loop and the inner for is just 
           // executing one time.
             next();
          });

        });

    });
 }); 
});

我试图在内部循环之后调用另一个next()但是却抛出错误。有没有人知道为什么内循环只运行一次?

1 个答案:

答案 0 :(得分:0)

您需要管理两个回调。内部回调" nexts"和外部回调" next"。您正在内循环中调用外部回调。

试试这个:

    var Nightmare = require('nightmare');
 var nightmare = Nightmare({show:true})

var complexObject = {

 19:["11","12","13","14","15"],
 21:["16"],
 22:["17"],
 23:["18","19"]
};
//looping on each object property
async.eachOfSeries(complexObject, function(item, keyDo, next){
  //here im looping on each key of the object, which are arrays
  async.eachOfSeries(item, function(indexs, key, nexts){
    nightmare
    .//do something
    .then(function(body){

        nightmare
        .//do something
        .then(function(body2){

           nightmare
          .//do something
          .then(function(body3){

            //Here I call next() and expecting to call the next index of the inner loop
            //but is calling the next index of the outer loop and the inner for is just 
           // executing one time.
             nexts();
          });

        });

    });
 }); 
next();
});