首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >node.js中带有异步模块的嵌套For循环

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

Stack Overflow用户
提问于 2016-10-11 14:13:31
回答 1查看 598关注 0票数 1

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

根据我所读过的内容,我必须调用next()函数,以便通知asyncOfSeries循环继续进行下一个索引。这是很好的工作,只有一个循环。当我嵌套asyncOfSeries时,内部next()函数不是在内环上执行,而是在外部循环上执行。

请查看代码片段,以便更好地理解:

代码语言:javascript
运行
复制
 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(),但正在抛出一个错误。有人知道为什么内环只运行一次吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-11 14:57:19

您需要处理两个回调。内部回调“接续”和外部回调“下一步”。您正在从内部循环中调用外部回调。

试试这个:

代码语言:javascript
运行
复制
    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();
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39979288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档