【问题标题】:Nested For loop with async module in node.jsnode.js 中带有异步模块的嵌套 For 循环
【发布时间】:2016-10-11 22:57:19
【问题描述】:

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

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

请看代码的sn-p,以便更好地理解:

 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(),但抛出了一个错误。有谁知道为什么内部循环只运行一次?

【问题讨论】:

  • 在哪里声明变量nightmare
  • 我已经编辑了sn-p。 @stdob--
  • 由于您使用的是 Promise,因此您可能不应该使用 async.js。它们的组合不好(而且你根本不处理错误)。
  • 你打错了:nexts 而不是next。您必须在内部回调中调用内部next,并且必须将外部next 作为回调传递给eachOfSeries

标签: node.js asynchronous async.js


【解决方案1】:

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

【讨论】:

  • 绝对合法,实际上我在此处粘贴代码时有错字,但在我的代码中,我有两个同名的回调 next()。我想因为它们在引起问题的同一范围内,我会试试这个。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
  • 2014-02-06
  • 2014-10-27
  • 1970-01-01
  • 2016-06-17
  • 2019-03-15
  • 1970-01-01
相关资源
最近更新 更多