1

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

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

这需要通过接口向 Hapi (v.13.0.0) 返回一个承诺reply()。我已经看到了 Bluebird 和其他 Promise 库的示例,例如:如何从 hapi.js 路由处理程序外部回复,但在调整 vo.js 时遇到问题。有人可以提供一个例子吗?

服务器.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
        })
    }
};
4

1 回答 1

2

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

服务器.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);
            })
        })
    }
};
于 2016-02-11T21:01:42.340 回答