Gemma
Gemma

Reputation: 43

Function not returning pg-pool results

I'm trying to use pg-pool to query a Postgresql database. And then export this data to a Node.js express rest API.

Here's my exports function.

exports.getDashboard = function(req, response, next) {
  let returnData = fetchData();
  return response.status(200).json(returnData);
};

Which calls fetchData();

fetchData = async function() {
    let returnData = [];
    returnData.languages = await getLatestLanguages();
    return returnData;
};

Which calls getLatestLanguages()

getLatestLanguages = function() {
  pgPool.pool.query(
    'SELECT * FROM "WordLanguage" ORDER BY id DESC LIMIT 30 ;',
    (error, results) => {
      if (error) {
        throw error;
      }
      return results.rows;
    }
  );
}

If i place a console.log(results.rows) before getLatestLanguages() returns results.rows, then I get the data logged to the console.

However the object isn't being returned to fetchData. I tested this by logging the returnData to console before it is returned to exports.getDashboard();

I believe my problem is something to do with the async nature of pg-pool so I tried making my function async with an await but that didn't help.

What am I doing wrong?

Upvotes: 4

Views: 1584

Answers (2)

TidyDev
TidyDev

Reputation: 3678

getLatestLanguages() should return a promise. For example

getLatestLanguages = function() {
  return new Promise((resolve, reject) => {
    pgPool.pool.query(
      'SELECT * FROM "WordLanguage" ORDER BY id DESC LIMIT 30 ;',
      (error, results) => {
        if (error) {
          reject(error);
        }
        resolve(results.rows);
      }
    );
  });
};

fetchData() is async and therefore should be awaited

exports.getDashboard = async function(req, response, next) {
  let returnData = await fetchData();

  return response.status(200).json({ languages: returnData.languages });
};

Also make sure that you return returnData.languages in the correct format as above instead of ...json(returnData);

Upvotes: 1

Gonzalo.-
Gonzalo.-

Reputation: 12682

you need getLatestLanguages to return a Promise, so you can await it from the caller

getLatestLanguages = function() {
    return new Promise((resolve, reject) => {
        pgPool.pool.query(
            'SELECT * FROM "WordLanguage" ORDER BY id DESC LIMIT 30 ;',
            (error, results) => {
              if (error) {
                reject(error);
              }
              resolve(results.rows);
            }
          );
    }) 
  }

you also need to await fetchData(), therefore getDashboard should be async

exports.getDashboard = async function(req, response, next) {
  let returnData = await fetchData();
  return response.status(200).json(returnData);
};

Upvotes: 2

Related Questions