I have 2 database collections and I want to use the result of the first query, as input to the second query, while ensuring the whole code runs sequentially. Here's what my code looks like:
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 });
}
});
Currently, the code works sequentially till it reaches (const squery = await db2.find({field:f});) instead of waiting for it to finish, it goes on to the logs after the filter function, in a sequence as I have commented beside each console.log. I want it to finish the filter function first, then print and send the result to the user. How can I do that?
You can pass two parameters in console log
Assign numbers to check sequence Ex. Console.log(1,"message or object");
And Use filter with a collection of promises is to use Promise.all and then apply the function to your collection of results.
Refrence link How to use Array.prototype.filter with async?
Other case
If Issue related async/await in mongodb . I mention question related async/await refrence below.