Phantom.js-如何使用承诺而不是回调

Phantom.js - How to use promises instead of callbacks?

本文关键字:回调 承诺 js- 何使用 Phantom      更新时间:2023-11-27

我正在用以下代码测试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();
    }

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

嗯。由于phantom-proxy似乎没有遵循标准的function(err, result)节点回调签名,因此处理promising的库可能无法正常工作。有可能一些人能处理这种魔法,但我有点怀疑。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