Phantom.js - 如何使用promises而不是回调?

时间:2016-04-04 03:44:12

标签: javascript node.js phantomjs

我正在使用以下代码测试phantom-node

var http = require('http');
http.createServer(function (req, res) {
  res.write('<html><head></head><body>');
  res.write('<p>Write your HTML content here</p>');
  res.end('</body></html>');
}).listen(1337);

var phantomProxy = require('phantom-proxy');

phantomProxy.create({'debug': true}, function (proxy) {
    proxy.page.open('http://localhost:1337', function (result) {
        proxy.page.render('scratch.png', function (result) {
                proxy.end(function () {
                    console.log('done');
                });
        }, 1000);
    });
});

它有效,但我想将其更改为:

phantomProxy.create()
   .then(something)=>{...}
   .then(something)=>{...}
   .then(something)=>{...}
   .catch((err)=>{
        console.log(err);
        proxy.end();
    }

这样更容易阅读。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

嗯。处理promisifying 的库可能无法正常工作,因为phantom-proxy似乎不遵循标准的function(err, result)节点回调签名。 可能可以处理那种魔法,但我会有点怀疑。我有点惊讶phantom-proxy没有错误作为这些回调的第一个参数。

无论哪种方式,你总是可以自己做。

function phantomProxyCreate(opts) {
    return new Promise(resolve => phantomProxy.create(opts, resolve));
}

function proxyPageOpen(url) {
    return (proxy) => {
        // You may need to resolve `proxy` here instead of `result`.
        // I'm not sure what's in `result`.
        // If that's the case, write out the callback for `proxy.page.open`,
        // and then `resolve(proxy)` instead.
        return new Promise(resolve => proxy.page.open(url, resolve)); 
    };
}

如果您遵循该样式,则可以执行此操作(请注意,我将从proxyPageOpen返回“curried”函数以在promise管道中使用):

phantomProxyCreate({ debug: true })
    .then(proxyPageOpen('http://localhost:1337'))
    // ... etc
相关问题