kaynew kaynew - 1 year ago 91
Javascript Question

Bluebird Request Function

I have a follow on question from this post: Chaining Requests using BlueBird/ Request-Promise

I am very new to promises, so please forgive the naivete. I am successfully able to implement this code:

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

.spread(function (responseRequest1, responseRequest2) {
// Proceed with other calls...
.catch(function (err) {
// Will be called if at least one request fails.

But in my case, the particular urls are different every time. I would like to take my fresh array of URLs, construct the options object for each, and then rp( ).

When I literally construct an array like this one -
var freshArray =[rp({Uri1 w/options}), rp({Uri2 w/options}), etc]
and stick it into the .all( ) above - no luck. I think the rp()'s are being implemented independent of the BPromise.all call?

How do I dynamically embed a constructed array of promises into the code above?

Answer Source

I'm not really sure about what you want to do, but would

BPromise.all([optionsForRequest1, optionsForRequest2].map((url) => {
  const urlWithOptions = someFunction(url);
  return rp(urlWithOptions);
.spread(function (responseRequest1, responseRequest2) {
    // Proceed with other calls...
.catch(function (err) {
    // Will be called if at least one request fails.

work? If so, you can even shorten it using (url) => rp(someFunction(url)) inside the map

=== edit ===

  • (x) => y is an es6 shorthand that is most of the time like function(x) { return y; }
  • (x) => { ... return y; } is a similar shorthand that let you have intermediary variables.
  • more on es6 on the internet :) like here

  • .map is a function defined on arrays. It applies the function to each element, so [1, 2].map((x) => x + 1) returns [2, 3]

So the code is like

var urls = [optionsForRequest1, optionsForRequest2];
var urlsWithOptions = [];
for (var k in urls) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download