在我的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?
答案 0 :(得分:1)
在最终结果中包含PG查询中的ID的一种方法是在processIDs
调用中设置另一个承诺,例如:
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)
});
}