2016-04-04 27 views
3

我这个代码测试phantom-nodePhantom.js - 如何使用promise而不是回调?

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

,使其更易于阅读。任何建议?

+0

您可能希望有看看“异步”模块,我记得内置在node.js中。它允许你做一些类似于你想要的东西。 –

+0

可能有一个库可以为你做,但它很容易创建你自己的承诺并包装所有这些功能。你想使用像ES6承诺还是像蓝鸟这样的图书馆? – Spidy

+0

我认为不是ES6。但我绝对想要最简单的事情开始。 – sooon

回答

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返回一个“令行禁止”功能的承诺管道使用):

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