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

我有一个asynchronous的nightmare.js过程,它使用vo.jsstream程控制和一个生成器:

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

这需要使用reply()接口返回对Hapi(v.13.0.0)的承诺。 我已经看到Bluebird和其他承诺库的例子,例如: 如何从hapi.js路由处理程序之外进行回复 ,但是无法适应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转换为返回承诺。 像这样(未经testing):

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); }) }) } };