0

In my NodeJS app I need to make a query to Postgres and then I need to make GET request for every row in the PG result. And return all GET results in an array.

What's wrong with my code?

var promise = require('bluebird');
var pgp = require('pg-promise')({ promiseLib: promise });
var db = pgp(connectionString);
var rp = require('request-promise');

var query = 'select id from my_table';

var processIDs = pgResults => {
    var requests = pgResults.map( row => rp(`mysite.com/${row.id}`) );
    return promise.all(requests);
}

db.any(query)
  .then(processIDs)
  .then( results => console.log(results) );

The second question, how to include IDs from PG query in the final result array?

  • Possible duplicate of [How do I access previous promise results in a .then() chain?](http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain) – vitaly-t Sep 13 '16 at 22:20

1 Answers1

1

One way to include ids from your PG query in the final result is to have another promise inside processIDs call, like that:

var processIDs = (result) => {
    var ids = result.map(row => row.id);
    var requests = ids.map(id => request(`mysite.com/${id}`));
    return promise.all(requests)
        .then(results => {
            // not sure how u want to include `ids` in results, but its available in this scope
            // just think that it's weird, cuz `results` is supposed to be
            // an array of HTTP responses, right?
            return results; // results.concat(ids) || results.push(ids)
        });
}
juanmaia
  • 56
  • 3