node.js - Bluebird 问题并请求获得休息响应

标签 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);
        });

而且它有效:) 但我必须确保调用是同步的,所以我想使用 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/

相关文章:

javascript - 请求 promise 未处理的拒绝 RequestError : Error: ETIMEDOUT

javascript - 使用 superagent-bluebird-promise 在 Node 服务器上处理服务器重定向

javascript - 如何处理依赖于另一个 promise 的 promise 循环

node.js - 使用 Selenium 和 Node 进行 Chromedriver 模拟

java - HttpServletResponse 到 javax.ws.rs.core.Response

rest - 如何保护我的自定义 Magento2 REST api

node.js - 按日期范围的小时数进行分组

node.js - 异步功能不起作用

ruby-on-rails - 资源 id 应该出现在 url 中吗?

javascript - 如何将现有回调 API 转换为 Promise?