Node.js&共同避免混合承诺和事件回调

时间:2017-12-18 14:07:32

标签: javascript node.js callback promise phantomjs-node

最近,我一直在试验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管理的领域?

1 个答案:

答案 0 :(得分:2)

  • 不再使用co +生成器功能。 async / await就在这里。
  • 是的,您应该将所有触发(最多)一次的事件回调转换为承诺。
  • 不,不要创造这样的承诺,并且&#34;在外部解决它们&#34;。只需将解析它们的东西放在promise构造函数中。

(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');
}());