节点 - 数据库查询回调未触发

时间:2017-10-14 19:26:27

标签: javascript node.js postgresql

这可能是一个愚蠢的问题,但我无法找到答案。 当我从另一个回调调用查询函数本身时,我的数据库查询(node - > PostgreSQL)没有触发回调:

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);
            }
    });
});

}

谢谢! :)

1 个答案:

答案 0 :(得分:1)

您是否已建立连接?在尝试运行查询之前,您需要先执行此操作。在这里查看示例: http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/#.WeJpJWhSyUk

npm pg-promise

另外,我强烈建议您使用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("/"); }); }); 。会简化你的生活。

最后,你也错过了承诺的意义。我鼓励你使用更新的async / await。但是,如果你不想和/或不能,至少要明白为什么你只是回到了一个回调地狱...承诺到位有助于减少所有的回叫嵌套。真的,你应该减少承诺的嵌套水平,如下:

NSArray / NSDictionary