噩梦在while循环中运行函数队列(让循环等到队列结束)

时间:2015-02-17 18:16:26

标签: javascript node.js nightmare

我试图在一个循环中运行噩梦。我的问题是while循环不是等待噩梦完成。 这是我的示例代码:

var Nightmare = require('nightmare');
var Screenshot = require('nightmare-screenshot');
var i = 0;

while(i < 10) {

    var nightmare = new Nightmare();
    nightmare.goto('https:/website/?id='+  i);
    nightmare.screenshot('/home/linaro/cointellect_bot/screenshot1.png');
    nightmare.use(Screenshot.screenshotSelector('screenshot' + i + '.png', 'img[id="test"]'));
    nightmare.run();
}

是否有可能让循环等到噩梦完成它的功能队列?我还有其他选择吗?

2 个答案:

答案 0 :(得分:2)

使用函数而不是循环:

var nightmare;
var Nightmare = require('nightmare');
var Screenshot = require('nightmare-screenshot');

var runNext = function (i) {
    if (i < 10) {
        nightmare = new Nightmare();
        nightmare.goto('https:/website/?id='+  i);
        nightmare.screenshot('/home/linaro/cointellect_bot/screenshot1.png');
        nightmare.use(Screenshot.screenshotSelector('screenshot' + i + '.png', 'img[id="test"]'));
        nightmare.run(function () {runNext(i+1);});        
    }
}
runNext(0);

nightmare.run根据此文档接受回调:https://github.com/segmentio/nightmare#runcb

作为参数传递的函数会在梦魇结束或出错后被调用。

这通常是nodejs中大多数异步事物的工作方式。

答案 1 :(得分:1)

虽然你需要提取一个函数,但最好不要只是传入一个数字而是传递完整的上下文。因此,您的功能将如下所示

var screenshotPage = function(data){
  var nightmare = new Nightmare();
  nightmare.goto(data.url);
  nightmare.use(Screenshot.screenshotSelector(data.filePath, data.selector));
  nightmare.run();
}

你应该可以运行这样的例子

var Nightmare = require('nightmare');
var Screenshot = require('nightmare-screenshot');
var async = require('async')

var pages = [];

// You could do this recursively if you want
for(var i=0; i < 10; i++) {
    pages.push({
        url: 'https://website/?id='+ i,
        filePath: 'screenshot' + i + '.png',
        selector: 'img[id="test"]'
    });
}

var screenshotPage = function(data, callback){
  var nightmare = new Nightmare();
  nightmare.goto(data.url);
  nightmare.use(Screenshot.screenshotSelector(data.filePath, data.selector));
  nightmare.run(function(){
    callback(null);
  });
}

async.map(pages, screenshotPage, function(){
  // Here all screenshotPage functions will have been called 
  // there has been an error
});