Phantom.js - 如何使用Promise代替回调函数?

3

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

为了更易读懂,有什么建议吗?

你可能想看一下内置在node.js中的"async"模块。它允许你做类似于你想要的事情。 - J. Lee
可能有一个库可以为您完成这项工作,但创建自己的承诺并包装所有这些函数非常简单。您想要使用像ES6承诺或类似Bluebird的库吗? - Spidy
我认为这不是ES6。但我肯定想要尽可能简单的东西来开始。 - sooon
1个回答

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返回了一个“柯里化”函数,在promise管道中使用):
phantomProxyCreate({ debug: true })
    .then(proxyPageOpen('http://localhost:1337'))
    // ... etc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接