0

在我的 NodeJS 应用程序中,我需要对 Postgres 进行查询,然后我需要对 PG 结果中的每一行进行 GET 请求。并在一个数组中返回所有 GET 结果。

我的代码有什么问题?

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

第二个问题,如何在最终结果数组中包含来自 PG 查询的 ID?

4

1 回答 1

1

在最终结果中包含 PG 查询中的 id 的一种方法是在processIDs调用中添加另一个 promise,如下所示:

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)
        });
}
于 2016-09-13T21:20:18.393 回答