2014-10-16 84 views
2

我使用这个框架来制作几个网址的截图。采取截图的过程是异步,并且该方法不提供一种方式来执行的回调,我想执行的回调时,每个屏幕截图是在这个脚本制作:NightmareJS截图回调

nightmare = new Nightmare(); 
urls.forEach(function (url) { 
    nightmare.goto(url).screenshot(path); 
}); 

nightmare.run(function() { 
    console.log('finished all'); 
}); 

任何想法如何,我可以做这个?

回答

3

我找到了一种方法来执行此操作,并使用“use”方法执行插件。

nightmare = new Nightmare(); 
urls.forEach(function (url) { 
    nightmare.goto(url).screenshot(path).use(function() { 
     console.log('finished one'); 
    }); 
}); 

nightmare.run(function() { 
    console.log('finished all'); 
}); 
1

这似乎是run()方法的目的。你可能想建立和运行循环中每个屏幕截图,因为screenshot()方法依赖于phandomjs方法render(),并render() is strictly synchronous(至少在一年的前):

urls.forEach(function (url) { 
    nightmare = new Nightmare(); 
    nightmare.goto(url).screenshot(path).run(function(err, nightmare) { 
     console.log('this executes when your screenshot completes'); 
     // run() appropriately tears down the nightmare instance 
    }); 
}); 

console.log('finished all'); 

你不会获得任何从一次设置所有屏幕截图获得异步好处,并且“全部完成”保证只在所有屏幕截图都呈现完毕后才运行。

或者,在nightmarejs源,它看起来像screenshot()确实采取这似乎是一个回调第二done参数,但它直接传送到phantomjs render()方法,和如在上述链路看出有一些阻止允许该方法进行回调的阻力。

+0

运行命令意味着在年底 – fernandopasik 2014-10-16 18:20:58

+0

只使用一次现在,我已经调查了源,而不是依靠例子,似乎调用运行在一个循环将可能存在的问题。您可以通过为每个屏幕截图设置一个新的Nightmare实例来解决这个问题。此外,'screenshot()'方法*会带走第二个'done'参数,它看起来像一个回调,尽管它直接传递给phantomjs,我不知道它是如何处理的。它所调用的render()方法是同步的,所以无论如何你在每次迭代中间都会有一个很大的同步动作。 – Jason 2014-10-16 19:04:41

+0

我已经用我在源代码中看到的东西更新了我的答案。 – Jason 2014-10-16 19:10:33