【问题标题】:Chaining Requests using BlueBird/ Request-Promise使用 BlueBird/Request-Promise 链接请求
【发布时间】:2016-11-10 11:01:39
【问题描述】:

我正在使用 request-promise 模块,但没有发现如何链接请求。我目前正在遵循他们的语法:

request({options})
  .then(function(result){...})
  .catch(function(error){...})

但是,我希望能够使用 Promise.all 并尝试同时拨打多个电话并等待它们全部解决,然后继续进行其他电话。例如我想:

  1. 调用一个创建用户的应用。
  2. 同时,拨打电话创建地址。
  3. Promise.all([UserCall, AddressCall]).then({处理结果的函数])?

我也一直在使用 module.exports = {...} 中的函数。这是否需要我在导出之外并将它们声明为单独的变量?

据我了解,似乎我必须做类似的事情:

var UserCall = function(req,res){
  return new Promise(function (resolve, reject){
    request({options})? //To make the call to create a new user?
  // Then something with resolve and reject

非常感谢任何帮助。我想我可能会混淆基本的 BlueBird 概念并尝试将它们与 request-promise 一起使用。

【问题讨论】:

  • 是的,只需使用Promise.all([request({…}), request({…})])。究竟是什么问题?你试过什么?
  • 不,如果request(…) 已经返回了一个promise,你不应该使用new Promise 构造函数
  • 我尝试使用Promise.all([request({…}), request({…})]).then(function(results){...})。但是由于某种原因,我从 2 个请求中得到了 null 或未定义的结果。我做了一些控制台日志,似乎 .then 函数没有等待结果返回。我应该为每个request({...}) 放置一个.then(function (result){ return result}) 吗?
  • 嗯,你可以试试,但实际上Promise.all 应该在输入上自己调用.then
  • 好的,我通过 Promise.all([function1, function2]).then({...}) 让它工作,其中 function1 和 function2 有 return request({...})

标签: javascript promise bluebird


【解决方案1】:

给你:

var BPromise = require('bluebird');
var rp = require('request-promise');

BPromise.all([
    rp(optionsForRequest1),
    rp(optionsForRequest2)
])
    .spread(function (responseRequest1, responseRequest2) {
        // Proceed with other calls...
    })
    .catch(function (err) {
        // Will be called if at least one request fails.
    });

【讨论】:

    【解决方案2】:

    如您所说,您可以使用all API 完成此操作。

    请参阅此处的文档:http://bluebirdjs.com/docs/api/promise.all.html

    示例:

        var self = this;
        return new Promise(function(resolve) {
            Promise.all([self.createUser, self.createAddress])done(
                // code path when all promises are completed
                // OR should any 1 promise return with reject()
                function() { resolve(); }
            );
        })
    

    如代码中所述,.all() 回调代码路径也将在 promises 中定义的任何 1 个承诺被拒绝时被调用。

    【讨论】:

    • 正如@Bergi 所说,您不应该创建新的承诺。只需致电Promise.all( self.createUser(), self.createAddress() ).then( ... )
    • 我目前正在做Promise.all([request({…}), request({…})]).then(function(result){...}).catch(function(err){...}),但我在上面的评论中所述的 2 个请求遇到了 null 或未定义的结果。
    • Promise.all 确实需要一个数组,而不是多个参数
    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多