如何以承诺和vo.js回复Hapi回复

时间:2016-02-11 09:36:21

标签: node.js asynchronous promise hapijs nightmare

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

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

这需要使用reply()接口向Hapi(v.13.0.0)返回一个承诺。我见过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
        })
    }
};

1 个答案:

答案 0 :(得分:2)

如果您想将doCrawl的结果发送给hapi的reply方法,则必须转换doCrawl以返回承诺。像这样(未经测试):

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