2016-04-04 26 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 
相關問題