在Postgres的回调中使用async / await

时间:2019-07-02 10:05:02

标签: javascript node.js database postgresql backend

我需要等待来自Postgres中使用回调函数的数据库中的查询。

我具有从数据库(queries.js)获取行的功能:

const getRecipesByCategoryForSection = (callback, category) => {    

    pool.query("SELECT * FROM recipes WHERE category=$1 ORDER BY RANDOM() LIMIT 10;", [category], (error, results) => {

        if (error) {
            console.log(error);
            throw error;
        }
        callback(results.rows);
    })
}

如您所见,我正在使用回调函数从数据库中获取行。我想使用这些行将它们显示在一页上,但是显示各种类别。我通过以下方式在server.js中使用它:

app.get("/recipes", function (req, res) {
        var breakfasts = [];
        var lunches = [];
        var desserts = [];

        db.getRecipesByCategoryForSection(function (rows) {            
            breakfasts = rows;      
        }, 'breakfast');


         db.getRecipesByCategoryForSection(function (rows) {
             lunches = rows;
         }, 'lunch');

         db.getRecipesByCategoryForSection(function (rows) {
             desserts = rows;
         }, 'snack');


        res.render("recipes", {
            breakfasts: breakfasts,
            lunches: lunches,
            snacks: snacks
        });
});

但是在这种配置中,变量breakfastslunchesdesserts当然不包含任何内容。

如何针对回调设置queries.js中的函数,以便server.js中的函数在执行其余代码之前将等待行?

我将非常感谢您的帮助,对此我还很陌生,因此任何解释和帮助都将非常宝贵。谢谢。

1 个答案:

答案 0 :(得分:-1)

您将需要在回调函数中包括如下所示的函数调用,这将解决此问题。但是不建议这样做,因为它会导致回调地狱,在这种情况下可能很难阅读。理想情况下,您应该将编码样式更改为异步/等待,以便代码干净。

app.get("/recipes", function (req, res) {
    var breakfasts = [];
    var lunches = [];
    var desserts = [];

    db.getRecipesByCategoryForSection(function (rows) {            
        breakfasts = rows;
        db.getRecipesByCategoryForSection(function (rows) {
            lunches = rows;
            db.getRecipesByCategoryForSection(function (rows) {
                desserts = rows;
                res.render("recipes", {
                    breakfasts: breakfasts,
                    lunches: lunches,
                    snacks: snacks
                });
            }, 'snack');
        }, 'lunch');      
    }, 'breakfast');    
});