gpt4 book ai didi

node.js - 如何使用promise和vo.js返回Hapi回复

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:34 27 4
gpt4 key购买 nike

我有一个异步的 night.js 进程,它使用 vo.js使用生成器进行流量控制:

vo(function *(url) {
return yield request.get(url);
})('http://lapwinglabs.com', function(err, res) {
// ...
})

这需要使用 reply() 接口(interface)向 Hapi (v.13.0.0) 返回一个 promise 。我看过 Bluebird 和其他 promise 库的示例,例如:How to reply from outside of the hapi.js route handler ,但在适应 vo.js 时遇到困难。有人可以提供一个例子吗?

server.js

server.route({
method: 'GET',
path:'/overview',
handler: function (request, reply) {
let crawl = scrape.doCrawl({"user": USERNAME, "pass": PASSWORD});
reply( ... ).code( 200 );
}
});

scrape.js

module.exports = {
DoCrawl: function(credentials) {
var Nightmare = require('nightmare');
var vo = require('vo');

vo(function *(credentials) {
var nightmare = Nightmare();
var result = yield nightmare
.goto("www.example.com/login")
...
yield nightmare.end();
return result

})(credentials, function(err, res) {
if (err) return console.log(err);
return res
})
}
};

最佳答案

如果您想将 doCrawl 的结果发送到 hapi 的 reply 方法,则必须将 doCrawl 转换为返回一个 Promise。像这样的东西(未经测试):

server.js

server.route({
method: 'GET',
path:'/overview',
handler: function (request, reply) {
let crawl = scrape.doCrawl({"user": USERNAME, "pass": PASSWORD});
// crawl is a promise
reply(crawl).code( 200 );
}
});

scrape.js

module.exports = {
doCrawl: function(credentials) {
var Nightmare = require('nightmare');
var vo = require('vo');

return new Promise(function(resolve, reject) {

vo(function *(credentials) {
var nightmare = Nightmare();
var result = yield nightmare
.goto("www.example.com/login")
...
yield nightmare.end();
return result

})(credentials, function(err, res) {
// reject the promise if there is an error
if (err) return reject(err);
// resolve the promise if successful
resolve(res);
})
})
}
};

关于node.js - 如何使用promise和vo.js返回Hapi回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335495/

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