【发布时间】: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
});
});
但在此配置中,变量 breakfasts、lunches 和 desserts 当然什么都不包含。
我如何设置queries.js 中的函数与回调相关,以便server.js 中的函数在执行其余代码之前等待行?
我会很感激任何帮助,我对此很陌生,所以任何解释和帮助都会非常有价值。谢谢。
【问题讨论】:
-
Convert the API to uses promises 然后使用
Promise.all同时运行它们。 -
谢谢,虽然我在这个据说是重复的问题中只看到了我的问题的一半答案。我还是不知道怎么用。
标签: javascript node.js database postgresql backend