最近,我一直在试验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
回调最终被调用时,主幻影过程已经退出。
为了“解决”这个问题,我采用了以下即兴策略(省略了下面示例的其余部分):
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}`);
这基本上创造了一个新的承诺,从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
管理的领域?
co
+ generator功能了。 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');
}());