我正试图在一段时间的循环中运行噩梦。我的问题是,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();
}是否有可能让循环等待直到噩梦完成它的函数队列?我还有别的选择吗?
发布于 2015-02-17 18:20:57
使用函数而不是循环:
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中大多数异步事物的工作方式。
发布于 2015-02-17 19:08:33
虽然您需要提取一个函数,但这可能是最好的,不只是传递一个数字,而是整个上下文。因此,您的函数将类似于
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
});https://stackoverflow.com/questions/28568283
复制相似问题