简体   繁体   中英

NestJS (NodeJS) client.query running 3 times and result is empty

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.

  1. 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.

  1. 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?

As for the second question you can do multiple async calls using async-await in the following way :

    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(async (client) => {
        try{
          for (let i = 0; i < queries.length; i++) {
            let res=await client.query(queries[i], values)
            if(res){
               client.release();
               queryResult.push(res['rows']);
               console.log('queryResult0', queryResult, queries.length);
            }
          }
          console.log('queryResult', queryResult);
          return queryResult;
        }
        catch(error){
          return error;
        }
    });
}

For the first question, I am not very sure what is causing that behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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