Node + Promise + Phantom.JS – 奇怪的错误

我使用Node和npm幻影制作了很多网页的截图。 为了节省CPU,我为每个进程使用一个Phantom实例。 在这种情况下,我打开一个页面,渲染它,closures它并继续。

除了当我开始另一个进程时,这个工作真的很棒。 在这种情况下,我得到这个错误,当一个过程完成时:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:2):错误:undefined不是一个对象(评估'target [command.params [0]]')

幻影实例:

function initPhantom(todos) { phantom.create(['--ignore-ssl-errors=no'], {logLevel: 'error'}) .then(function (instance) { var processId = instance.process.pid; console.log("===================> instance: ", processId); phInstance = instance; webshot(0, todos); }); } 

通过URL循环:

 function webshot(id, shots) { phInstance.createPage().then(function (_page) { sitepage = _page; sitepage.property('viewportSize', {width: 1024, height: 768}); WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'); sitepage.setting("resourceTimeout", 4000); return sitepage.open(shots[id].url); }) .then(function (status) { console.log("render %s / %s", id + 1, shots.length); setTimeout(function () { var image = 'temp_img/' + shots[id]._id + '.png'; sitepage.render(image, {format: 'png', quality: '30'}).then(function (finished) { sitepage.close(); chekcImageinDb(shots[id], image); if (id < shots.length - 1) { id += 1; webshot(id, shots); } else { console.log("===================> all done: %s files has been written", shots.length); phInstances.shift(); if(phInstances.length < 1){ console.log("kill phantom ", phInstances); //phInstance.exit(); } } }); }, 2000); }) } 

任何想法

——–编辑———–

好的,我尝试了你的build议,同样的错误。 正如您在日志中所看到的,只有在一个过程完成后才会发生。

 function webshot(id, shots) { phInstance.createPage().then(function (_page, error) { if(error){ console.log("first", error); } sitepage = _page; sitepage.property('viewportSize', {width: 1024, height: 768}); WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'); sitepage.setting("resourceTimeout", 4000); return sitepage.open(shots[id].url); }).catch(function(e) { console.log(e); }).then(function (status, error) { if(error){ console.log(error) } console.log("render %s / %s", id + 1, shots.length); setTimeout(function () { var image = 'temp_img/' + shots[id]._id + '.png'; sitepage.render(image, {format: 'png', quality: '30'}) .then(function (finished, error) { if(error){ console.log(error) } sitepage.close(); chekcImageinDb(shots[id], image); if (id < shots.length - 1) { id += 1; webshot(id, shots); } else { console.log("===================> all done: %s files has been written", shots.length); phInstances.shift(); if(phInstances.length < 1){ console.log("kill phantom ", phInstances); //phInstance.exit(); } } }).catch(function(e) { console.log(e); }); }, 2000); }).catch(function(e) { console.log(e); }) } 

以下是几乎同时启动的两个实例的日志文件。 就像我说的,如果只有一个进程正在运行,一切都很好。

在这里输入图像描述

我认为你需要传递第二个callback函数到你的then函数调用失败处理程序。 根据接口,你可能需要在你的then()调用之后链接一个.catch(function(){})