2016-02-11 48 views
1

我有一個使用vo.js流量控制與發電機異步nightmare.js過程:如何返回哈啤與承諾答覆和vo.js

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

這需要一個承諾返回哈皮(v.13.0 .0)與reply()接口。我見過Bluebird和其他承諾庫的例子,例如: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 
     }) 
    } 
}; 
+0

你能不能創建一個新的承諾,在這個包裹返回值,然後可以用解決的價值調用回覆?!承諾不是很好,但我已經看到其他人在使用hapi回覆回覆的承諾時使用此方法。 –

回答

2

如果你想發送的doCrawl結果到高致病性禽流感的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); 
      }) 
     }) 
    } 
};