0

This may be a stupid question but I was not able to find an answer. My db query (node -> PostgreSQL) is not firing the callback when the query function itself is called from another callback like this:

routes.js

router.post("/getsheet/", (req, res) => {

    googleAPI.getSheet(googleToken, req.body.sheetid).then((invoices) => {

        templateData.sheetData = invoices;
        templateData.sheetData.length = invoices.length;

        // When sheet is received, db query runs but it's callback won't
        // function takes an array and index
        db.query(invoices, 1).then((db_results) => {
            console.log(db_results);
            res.redirect("/");
        }).catch((db_error) => {
            console.error(db_error)
            res.redirect("/");
        });

    }).catch((error) => {
        console.error(error);
    });
});

db.js

const query = (data, index) => {
return new Promise((resolve, reject) => {
    // console log fires but not the callback function so it does not resolve or reject
    console.log("... querying index ... " + index + " customer: " + data[index].name);
    client.query(`SELECT * FROM customer WHERE customer_number=${data[index].customer_id};`, (err, res) => {
            // does not run this block
            if (!err) {
                resolve(res);
            } else {
                return reject(err);
            }
    });
});

}

Thanks! :)

2
  • Your code in routes.js doesn't even call the query function you show after. Something is missing. And in general, instead of converting pg library into promises, it is better to use pg-promise ;) Commented Oct 14, 2017 at 19:37
  • These snippets are part of larger code and routes.js of course requires db.js in variable "db". Client connect and end are before and after query -function. Sorry I left those points out. Commented Oct 15, 2017 at 4:49

1 Answer 1

1

Have you already established a connection? You'd need to do that first before trying to run a query. See an example here: http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/#.WeJpJWhSyUk

  pg.connect(connectionString, (err, client, done) => {
    // Handle connection errors
    if(err) {
      done();
      console.log(err);
      return res.status(500).json({success: false, data: err});
    }
    // SQL Query > Select Data
    const query = client.query('SELECT * FROM items ORDER BY id ASC;');
    // Stream results back one row at a time
    query.on('row', (row) => {
      results.push(row);
    });
    // After all data is returned, close connection and return results
    query.on('end', () => {
      done();
      return res.json(results);
    });
  });

Also, I'd highly recommend you use npm pg-promise. Will simplify your life.

Lastly, you're also missing the point of promises. I'd encourage you to use the newer async/await. However if you don't want to and/or can't, at least see why you're just getting back into a callback hell... promises are in place to help reduce all the call back nesting. Really you should reduce the nest level of your promises, like so:

router.post("/getsheet/", (req, res) => {

    googleAPI.getSheet(googleToken, req.body.sheetid).then((invoices) => {

        templateData.sheetData = invoices;
        templateData.sheetData.length = invoices.length;

        // When sheet is received, db query runs but it's callback won't
        // function takes an array and index
        return db.query(invoices, 1);
    }).then((db_results) => {
        console.log(db_results);
        res.redirect("/");
    }).catch((error) => {
        console.error(error);
        res.redirect("/");
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, the db query works and connection is established before the query-function. Thanks I will try your advice and let you know how it went! :)
I marked this as the answer since you pointed me to right direction. Thanks! :) BTW: I ended up using the basic pg-module since it's possible to make "promise-queries" with it too like this: client.query(query).then((data)=>{...}).catch((e)=>{...})
@Mulperi pg-promise does a lot more than just promises: github.com/vitaly-t/pg-promise#about

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.