0

I'm trying to implement a promise-based approach to accessing a PostgreSQL database. This is the original code:

// ./sql/config/pgQuery.js
module.exports = (text, values, cb) => {
  pool.connect((err, client, done) => {
    if (err) return cb(err);
    client.query(text, values, (err, result) => {
      done();
      if (err) return cb(err);
      return cb(null, result.rows, result);
    });
  });
};

// ./routes/pg.js
router.route('/')
  .get((req, res) => {
    const values = [];

    query('DROP TABLE IF EXISTS users', values, (err, rows, all) => {
      if (err) throw err;
      console.log('DROP TABLE IF EXISTS users');
      res.status(204).end();
    });

    const text = 'CREATE TABLE IF NOT EXISTS users (date timestamptz)';
    query(text, values, (err, rows, all) => {
      if (err) throw err;
      console.log('CREATE TABLE IF NOT EXISTS users');
      res.status(204).end();
    });
  });

This is what I come up with so far, but it doesn't work:

// ./sql/config/pgQuery.js
function promisePool() {
  return new Promise((resolve, reject) => {
    return (text, values, cb) => {
      pool.connect((err, client, done) => {
        if (err) { cb(err); return; }
        client.query(text, values, (err, result) => {
          done();
          if (err) { reject(err); return; }
          return resolve(cb(null, result.rows, result));
        });
      });
    };
  });
}
module.exports = promisePool;

// ./routes/pg.js
router.route('/')
  .get((req, res) => {
    const values = [];
    query()
      .then('DROP TABLE IF EXISTS users', values, (err, rows, all) => {
        if (err) throw err;
        console.log('DROP TABLE IF EXISTS users');
        res.status(204).end();
      })
      .then('CREATE TABLE IF NOT EXISTS users (date timestamptz)', values, (err, rows, all) => {
        if (err) throw err;
        console.log('CREATE TABLE IF NOT EXISTS users');
        res.status(204).end();
      });
  });

Thank You for your help!

2
  • 2
    For promise-based coding for PostgreSQL use pg-promise instead. Commented Sep 27, 2016 at 19:26
  • If you write an answer I will accept it as the suggested library. I'm already using it. Commented Dec 4, 2016 at 16:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.