【问题标题】:How to return Hapi reply with promise and vo.js如何使用 Promise 和 vo.js 返回 Hapi 回复
【发布时间】:2016-02-12 05:01:42
【问题描述】:

我有一个异步的 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
        })
    }
};

【问题讨论】:

  • 你不能创建一个新的承诺并在其中包装返回值,然后你可以用解析的值调用回复吗?!对承诺不太好,但我看到其他人在从 hapi 的回复回调返回承诺时使用此方法。

标签: node.js asynchronous promise hapijs nightmare


【解决方案1】:

如果您想将 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);
            })
        })
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2020-08-06
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多