【发布时间】:2022-01-08 08:04:38
【问题描述】:
我有 2 个数据库集合,我想使用第一个查询的结果作为第二个查询的输入,同时确保整个代码按顺序运行。 这是我的代码的样子:
app.post("/Search", async (req, res) => {
criteria = req.body.criteria
c = req.body.c
total = req.body.total
try {
const fquery = await db.find(criteria);
console.log(fquery);//print 1
let r = fquery.filter(async function (element) {
let f = element.field;
console.log(f);//print 2
const squery = await db2.find({field:f});
console.log(squery);//print 6
let cond = squery.length == 0;//result set empty
if (c == value) {
cond2 = //some condition
}
else if (c == value2) {
cond2 = //another condition
}
else {
cond2 =//3rd condition
}
console.log(cond);//print 7
console.log(cond2);//print 8
return (cond || cond2);
})
console.log(fquery);//print 3
console.log("xxxx111");//print 4
console.log(r);//print 5
res.json(r);
} catch (err) {
res.json({ message: err });
}
});
目前,代码按顺序工作,直到到达 (const squery = await db2.find({field:f});) 而不是等待它完成,而是在过滤器函数之后继续记录日志,在我在每个 console.log 旁边评论过的顺序。 我希望它先完成过滤功能,然后打印并将结果发送给用户。我该怎么做?
【问题讨论】:
标签: javascript node.js mongoose async-await