最近,我一直在尝试phantomjs-node
图书馆。我想要实现的基本上是创建一个动态网页模板,使用phantomjs-node
库来“运行”它,最后从渲染的页面中提取一些数据。
在最简单的设置中,第一次尝试是这样的(在下面的示例中,模板只是静态的,但原则上它可能包含一些利用外部库的进一步逻辑等):
var phantom = require('phantom');
var co = require('co');
var sleep = require('system-sleep');
var winston = require('winston');
const logger = new winston.Logger({
level: 'debug',
transports: [new winston.transports.Console({
json: false, timestamp: () => (new Date()).toLocaleString()
})]
});
co(function*() {
logger.info('start');
var instance = yield phantom.create();
try {
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Page title</title>
</head>
<body>
<div id='results'>Page data</div>
</body>
</html>
`;
var page = yield instance.createPage();
yield page.on('onLoadFinished', function(){
logger.info('onLoadFinished');
page.evaluate(function(){
return document.getElementById('results').textContent;
}).then(function(val){
logger.info(`RESULT = ${val}`);
}).catch(function(val){
logger.error(val.message);
});
});
yield page.setContent(html, 'http://localhost');
}catch (e){
logger.error(e.message);
}finally{
instance.exit();
}
logger.info('done');
});
但是,输出失败:
12/18/2017, 2:44:32 PM - info: start
12/18/2017, 2:44:33 PM - info: done
12/18/2017, 2:44:33 PM - info: onLoadFinished
12/18/2017, 2:44:33 PM - error: Phantom process stopped with exit code 0
很可能是因为当最终调用then
返回的 promise 的 -callback时page.evaluate
,主幻象进程已经退出。
为了“解决”这个问题,我采用了以下即兴策略(省略下面示例的其余部分):
var page = yield instance.createPage();
var resolver;
var P = new Promise(function(resolve, reject){ resolver = resolve; });
yield page.on('onLoadFinished', function(){
logger.info('onLoadFinished');
resolver(page.evaluate(function(){
return document.getElementById('results').textContent;
}));
});
yield page.setContent(html, 'http://localhost');
const val = yield P;
logger.info(`RESULT = ${val}`);
这实质上创建了一个新的 Promise,该 Promise 由返回的 Promise “外部”解决page.evaluate
。yield P
块末尾的语句然后co
阻塞,直到所需的结果准备好,因此输出如预期:
12/18/2017, 2:53:47 PM - info: start
12/18/2017, 2:53:48 PM - info: onLoadFinished
12/18/2017, 2:53:48 PM - info: RESULT = .....
12/18/2017, 2:53:48 PM - info: done
虽然这似乎可行,但感觉很“hacky”(例如在调用之前在回调中抛出的异常resolver
不会在主try/catch
块中检测到),所以我想知道什么是更清洁的方法来“转移“控制从onLoadFinished
回调回到由管理的领域co
?