2016-09-13 57 views
0

在我的NodeJS應用程序中,我需要對Postgres進行查詢,然後我需要對PG結果中的每一行進行GET請求。並將數組中的所有GET結果返回。如何鏈接Postgres查詢,然後使用promise在NodeJS中獲取請求

我的代碼有什麼問題?

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?包括從最後的結果你的PG查詢IDS

+0

的[如何訪問的。於是先前承諾的結果可能重複()鏈?](http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain) –

回答

1

一種方法是有另一個承諾內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) 
     }); 
} 
+0

謝謝! 以及如何使整個代碼工作? –

+0

你得到什麼錯誤?在您的承諾鏈中包含'.catch(err => console.log(err))'調用,看看是否有任何錯誤。 – juanmaia

+0

我剛剛在我要求的服務中遇到錯誤。它現在有效。非常感謝! –

相關問題