bluebird问题并请求获得休息响应

时间:2015-12-24 14:54:44

标签: node.js rest bluebird

我使用'请求'使用以下代码请求休息服务的模块:

var request = require('request');
request.get('http://localhost:8190/api/1.0/product/012345',
        { auth: { user: 'toto', pass: 'totopass'} },
        function(error,response,body) {
            console.log(body);
        });

它有效:) 但我必须确保调用是同步的,所以我想使用一个承诺。 我写了下面的代码:

var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));
request.getAsync('http://localhost:8190/api/1.0/product/012345',
        { auth: { user: 'toto', pass: 'totopass'} }).then(function(error,response,body) {
            console.log(body);
        });

但它失败了,我看到了#undefined'是控制台。

1 个答案:

答案 0 :(得分:1)

默认情况下,promisifyAll会删除err参数,并且只返回一个参数。在宣传时尝试设置multiArgs,然后使用spread将结果数组传递到下一个函数,并将错误处理移到catch,例如:

var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'), {multiArgs: true});

request.getAsync('http://localhost:8190/api/1.0/product/012345',
    { auth: { user: 'toto', pass: 'totopass'} })
.spread(function(response, body) {
        console.log(body);
    })
.catch(function(err){
    console.log(err);
});