Phantom.js-如何使用承诺而不是回调
Phantom.js - How to use promises instead of callbacks?
我正在用以下代码测试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
相关文章:
- 承诺在非节点式回调上使用Bluebird
- 角承诺的“then”函数的成功回调的词汇范围是什么?
- JQuery 承诺已经包含回调的函数
- JavaScript - 返回承诺和/或调用回调
- 承诺中的成功回调不会发生$http
- 如何重构“;回调金字塔”;转换为基于承诺的版本
- 承诺在Protractor中进行回调排序
- Javascript承诺动态回调
- 编写一个使用传递两个参数的回调的承诺
- Phantom.js-如何使用承诺而不是回调
- 在第一次错误回调时退出承诺链
- 如何获取 Ember 组件对象内部承诺成功或错误回调
- 创建承诺回调
- 回调/承诺无法正常工作
- 通知承诺角度删除回调
- 回调/承诺在快递.js中实现
- Node sequelize回调承诺期望一个函数,是否有一种方法可以通过函数调用删除已声明的函数
- Angular-For Loop HTTP回调/承诺
- 特定于Node-webkit的javascript回调/承诺问题
- 让javascript函数与回调/承诺实现总是返回一个承诺