【问题标题】:Using async/await in a callback with postgres [duplicate]在带有 postgres 的回调中使用 async/await [重复]
【发布时间】:2019-11-12 22:56:07
【问题描述】:

我需要等待来自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 中的函数在执行其余代码之前等待行?

我会很感激任何帮助,我对此很陌生,所以任何解释和帮助都会非常有价值。谢谢。

【问题讨论】:

  • Convert the API to uses promises 然后使用Promise.all 同时运行它们。
  • 谢谢,虽然我在这个据说是重复的问题中只看到了我的问题的一半答案。我还是不知道怎么用。

标签: javascript node.js database postgresql backend


【解决方案1】:

您需要在回调函数中包含函数调用,如下所示,这将解决问题。但不推荐这样做,因为它会导致难以阅读的回调地狱。理想情况下,您应该将编码样式更改为 async/await,以便代码干净。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多