我使用“请求”模块通过以下代码请求休息服务:
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);
});
而且它有效:) 但我必须确保调用是同步的,所以我想使用 Promise。 我写了下面的代码:
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);
});
但它失败了,我看到控制台是“未定义”。
最佳答案
它看起来像 promisifyAll
默认情况下会删除 err 参数,并仅返回一个参数。尝试在 promisifying 时设置 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);
});
关于node.js - Bluebird 问题并请求获得休息响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454552/