node.js 中带有异步模块的嵌套 For 循环

Nested For loop with async module in node.js

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

根据我读到的内容,我必须调用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() 但抛出错误。有谁知道为什么内部循环 运行 只是一次?

您有两个回调需要管理。内部回调 "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();
});