Tamas
Tamas

Reputation: 11214

Promises and arrays in Node.js

I am using Bluebird and request npm packages:

var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
Promise.promisifyAll(request);

I have a function that goes out to a REST endpoint and returns some data:

var getData = function() {
    options.url = 'http://my/endpoint';
    options.method = 'GET'; //etc etc...
    return request(options);
};

getData().then(function(response) {
  console.log(response); //-> this returns an array
});

response is an array that gets returned by the REST endpoint. The problem is that now I'd like to make a second request for each item in my array, so something like:

var getIndividualData = function(data) {
  data.forEach(function(d) {
    options.url = 'http://my/endpoint/d'; //make individual requests for each item
    return request(options);
  });
};

The above of course does not work and I understand why. However, what I don't understand is how can I make this work. Ideally what I'd like to have is a chain such as:

getData().then(function(response) {
  return getIndividualData(response);
}).then(function(moreResponse) {
  console.log(moreResponse); // the result of the individual calls produced by getIndividualData();
});

Upvotes: 2

Views: 274

Answers (1)

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10785

You can use Promise.all to wait for an array of promises to complete.

getData()
  .then(getIndividualData)
  .then(function(moreResponse) {
    // the result of the individual calls produced by getIndividualData();
    console.log(moreResponse);
   });

function getIndividualData(list) {
  var tasks = list.map(function(item) {
    options.url = // etc.
    return request(options);
  });

  return Promise.all(tasks);
}

Upvotes: 3

Related Questions