简体   繁体   English

如何使用Promise在NodeJS中链接Postgres查询和GET请求

[英]How to chain Postgres query and then GET requests in NodeJS using promises

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. 在我的NodeJS应用中,我需要查询Postgres,然后需要对PG结果中的每一行进行GET请求。 And return all GET results in an array. 并以数组形式返回所有GET结果。

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? 第二个问题,如何在最终结果数组中包含PG查询的ID?

One way to include ids from your PG query in the final result is to have another promise inside processIDs call, like that: 在最终结果中包含来自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)
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM