2016-07-08 33 views
1

我正在使用request-promise模块并且未发现如何链接请求。我目前正在跟随他们的语法:使用BlueBird/Request-Promise的链接请求

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

不过,我希望能够用Promise.all并试图在同一时间,使多个呼叫,等待他们所有的决心,然后用其他电话进行。例如,我想要:

  1. 拨打一个创建用户的应用程序。
  2. 在同一时间,拨打电话创建一个地址。
  3. Promise.all([UserCall,AddressCall])。then({function to deal with results])?

此外,我一直在使用我的功能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概念并尝试将它们用于请求承诺。

+0

是的,就用'Promise.all([请求({...}),请求({...})])'。究竟是什么问题?你有什么尝试? – Bergi

+0

不,你不应该使用'new Promise'构造函数,如果request(...)'已经返回一个承诺 – Bergi

+0

我尝试使用'Promise.all([request({...}),request({...})])。然后(函数(结果){...})'。但由于某种原因,我收到了2个请求中的空值或未定义结果。我做了一些控制台日志,好像.then函数没有等待结果返回。我是否应该为每个'request({...})'放置'.then(function(result){return result})? – Jeff

回答

-1

就像您所说的,您可以使用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()回调的代码路径将调用以及当确定承诺中的任何1 promises被拒绝。

+0

正如@Bergi所说,你不应该创造新的承诺。只需调用'Promise.all(self.createUser(),self.createAddress()).then(...)' – Arnial

+0

我正在执行'Promise.all([request({...}),request({... (函数(结果){...})。catch(函数(err){...})'但是我正在运行到2个请求中的null或undefined resullts,正如我在上面的注释中所述。 – Jeff

+0

'Promise.all'确实需要一个数组,而不是多个参数 – Bergi

2

在这里你去:

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. 
    });