node.jspostgresqlexpressnode-pg-pool

How to create multiple queries in a single GET request


I am using node-pg and would like to make multiple queries within a single GET request.

For example consider I make two queries like so:

const getSomeInfo = (request, response) => {
    
    pool.query('SELECT * FROM jobs', (error, results) => {
        if (error) {
            throw error
        }
        var jobObj = results.rows;
        response.render('pages/jobinfo', {
            jobObj: jobObj
        });
    })

    pool.query('SELECT * FROM description INNER JOIN views', (error, results) => {
        if (error) {
            throw error
        }
        var descObj = results.rows;
        response.render('pages/jobinfo', {
            descObj: descObj
        });
    })
    
}

This code results in the following error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.

Is there a way to make both these queries within the same GET request so that the objects containing the results can be used on the same page?


Solution

  • You can render only one document, but this can contain two local variables, one from each query. To have the queries executed in parallel, use Promise.all and make use of the fact that pool.query without a callback function returns a promise.

    const getSomeInfo = (request, response) => {
        
      Promise.all([
        pool.query('SELECT * FROM jobs'),
        pool.query('SELECT * FROM description INNER JOIN views')
      ]).then(function([jobResults, descResults]) {
        response.render('pages/jobinfo', {
          jobObj: jobResults.rows,
          descObj: descResults.rows
        });
      }, function(error) {
        throw error;
      });
        
    }