Search code examples
node.jspromisepg-promise

get result out of a pg-promise query


I am working on a Node project with pg-promise. I need to fulfill a promise with the results of the query, but I can't get the results out.

get2 : function(id) {
    var qrm = pgp.queryResult;
    PG.db.any('SELECT * FROM referentiel_rd_client WHERE id=\'' + id + '\'')
        .then(data => {
            console.log('got query results');
            resolve(data);
        })
       .catch(error => {
           // error; 
        });

But the other promise (that should receive the data) never gets anything... How do I get the results out of the query? (I can log them to the console).


Solution


    • If you want to pre-process the result, in the end just return the result, that's how promises work:

      get2: (id) => {
          return PG.db.any('SELECT * FROM referentiel_rd_client WHERE id=$1', id)
              .then(data => {
                  console.log('got query results:', data);
                  return data;
              });
      

    • Never format queries manually, use the query formatting engine that comes with the library, or you will end up breaking queries.

    Then you will call it like this:

    get2(123)
        .then(data => {
            // success
        })
        .catch(error => {
            // error
        });