gpt4 book ai didi

javascript - Phantom.js - 如何使用 promise 而不是回调?

转载 作者:搜寻专家 更新时间:2023-11-01 00:00:21 25 4
gpt4 key购买 nike

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

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

最佳答案

嗯。处理 promise 的库可能无法正常工作,因为phantom-proxy 似乎不遵循标准的function(err, result) Node 回调签名。 可能可以处理那种魔术,但我有点怀疑。我有点惊讶 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

关于javascript - Phantom.js - 如何使用 promise 而不是回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36394243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com