Chaining Requests using BlueBird/ Request-Promise

2019-06-07 14:57发布

问题:

I'm using the request-promise module and have found no mention of how to chain requests. I'm currently following their syntax of:

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

However I want to be able to use Promise.all and try to make multiple calls at the same time and wait for them to all resolve and then proceed with other calls. For example I want to:

  1. Make a call to one app creating a User.
  2. AT THE SAME TIME, make a call creating an Address.
  3. Promise.all([UserCall, AddressCall]).then({function to deal with results])?

Also I have been working with my function in module.exports = {...}. Does this require me to be outside of exports and have them declare as separate variables?

From what I understand its seems as if I have to do something like:

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

Any help is much appreciated. I think I may be mixing up basic BlueBird concepts and trying to use them with request-promise.

回答1:

Here you go:

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:

Like you said, you can accomplish this using the all API.

Refer to the documentation here: http://bluebirdjs.com/docs/api/promise.all.html

Example:

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

As noted in the code, the .all() callback code path will get called as well when any 1 of the defined promise in promises gets rejected.