最近,我一直在试验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
- page.evaluate
返回的承诺的回调时,主幻像进程已经退出。
为了修复&#34;为此,我采用了以下即兴策略(省略了下面示例的其余部分):
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}`);
这基本上创造了一个新的承诺,即外部&#34;解决了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
虽然这看起来很有效,但感觉非常好。&#34; hacky&#34; (例如,在调用resolver
之前在回调中抛出的异常不会在主try/catch
块中被检测到),所以我想知道什么是更清洁的方法才能#&# 34;传递&#34;从onLoadFinished
回调控制回到由co
管理的领域?
答案 0 :(得分:2)
co
+生成器功能。 async
/ await
就在这里。
(async function() {
logger.info('start');
var instance = await phantom.create();
try {
const html = `…`;
const page = await instance.createPage();
await new Promise((resolve, reject) => {
page.on('loadFinished', resolve);
page.on('resourceError', reject); // or something like that?
page.setContent(html, 'http://localhost'); // this doesn't appear to return a promise
})
logger.info('onLoadFinished');
try { // this extra inner try looks superfluous
const val = await page.evaluate(function(){
return document.getElementById('results').textContent;
});
logger.info(`RESULT = ${val}`);
} catch(e) {
logger.error(e.message);
}
} catch(e) {
logger.error(e.message);
} finally {
instance.exit();
}
logger.info('done');
}());