Reputation: 4888
I am testing phantom-node
with this code:
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);
});
});
It works, but I want to change it to something like:
phantomProxy.create()
.then(something)=>{...}
.then(something)=>{...}
.then(something)=>{...}
.catch((err)=>{
console.log(err);
proxy.end();
}
So that it is easier to read. Any suggestion?
Upvotes: 3
Views: 1556
Reputation: 5538
Hm. The libraries that handle promisifying may not work correctly, since phantom-proxy
doesn't seem to follow the standard function(err, result)
node callback signature. There might be some that handle that sort of magic, but I'd be a bit skeptical. I'm a little bit surprised that phantom-proxy
doesn't have an error as the first argument for those callbacks.
Either way, you can always do it yourself.
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));
};
}
If you follow that style, you can do this (note that I'm returning a "curried" function from proxyPageOpen to use in the promise pipeline):
phantomProxyCreate({ debug: true })
.then(proxyPageOpen('http://localhost:1337'))
// ... etc
Upvotes: 1