Javascript 在带有postgres的回调中使用async/await
我需要等待来自使用回调函数的Javascript 在带有postgres的回调中使用async/await,javascript,node.js,database,postgresql,backend,Javascript,Node.js,Database,Postgresql,Backend,我需要等待来自使用回调函数的Postgres中的数据库的查询 我有一个从数据库中获取行的函数(querys.js): 如您所见,我正在使用回调函数从数据库中获取行。我想使用这些行在一个页面上显示它们,但显示各种类别。我在我的server.js中以以下方式使用它: app.get("/recipes", function (req, res) { var breakfasts = []; var lunches = []; var desserts
Postgres
中的数据库的查询
我有一个从数据库中获取行的函数(querys.js
):
如您所见,我正在使用回调函数从数据库中获取行。我想使用这些行在一个页面上显示它们,但显示各种类别。我在我的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
});
});
但是在这种配置中,变量早餐
,午餐
,和甜点
当然不包含任何内容
如何在querys.js
中设置回调函数,以便server.js
中的函数在执行其余代码之前等待行
如果有任何帮助,我将不胜感激,因为我对这一点还不熟悉,所以任何解释和帮助都是非常有价值的。谢谢。您需要在回调函数中包含函数调用,如下所示,这将解决问题。但不建议这样做,因为这会导致回调地狱,在那里可能很难阅读。理想情况下,您应该将编码样式更改为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');
});
然后使用
Promise.all
来同时运行它们。谢谢,尽管我在这个重复的问题中只看到了我问题的一半答案。我还是不知道怎么用。
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');
});