I'm just diving into NestJS (and promises) and have everything working when I use one single client.query
. As Postgres cannot daisychain queries with params I need to run client.query
anywhere from 0 to n times which i'm trying to accomplish with a simple JS loop.
I have searched everywhere but have not been able to find how to do this with a loop (I might be searching for the wrong terminology...)
getQueryResult({
queries,
database,
values = []
}: {
queries: string[];
database: string;
values?: string[];
}): Promise<any> {
// Connect to remote Postgres via local SSH tunnel
const pool = new Pool({
user: '',
host: 'localhost',
database: database,
password: '',
port: 63333
});
const queryResult = [];
return pool.connect().then(client => { // <--THIS LINE RUNS 3 TIMES
for (let i = 0; i < queries.length; i++) {
client
.query(queries[i], values)
.then(res => {
client.release();
queryResult.push(res['rows']);
console.log('queryResult0', queryResult, queries.length);
})
.catch(err => {
client.release();
console.log(err);
});
}
console.log('queryResult', queryResult);
return queryResult;
});
}
I have two challenges.
- When
queries
contains one query: The query fires three times and yields the following
queryResult []
queryResult0 [
[
{ ... correct results ... }
]
] 1
queryResult0 [
[
{ ... correct results ... }
]
] 1
queryResult0 [
[
{ ... correct results ... }
]
] 1
where 1
is the (correct) length of the array.
- The last return
queryResult
is just the empty array - due to being returned before the loop has run I guess since it shows --^ before the loop. Out of scope/async is described all over SO but I cannot wrap my head around how to fix it in this particular case. Have read all of this How do I return the response from an asynchronous call?