【问题标题】:How can I ensure that my nodejs code runs sequentially while calling Mongoose?如何确保我的 nodejs 代码在调用 Mongoose 时按顺序运行?
【发布时间】: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


    【解决方案1】:

    你可以在控制台日志中传递两个参数

    分配编号以检查序列 前任。 Console.log(1,"消息或对象");

    并且 使用带有 promise 集合的过滤器是使用 Promise.all,然后将该函数应用于您的结果集合。

    参考链接How to use Array.prototype.filter with async?

    其他情况

    如果问题相关 async/await 在 mongodb 。 我在下面提到了与 async/await 相关的问题。

    Node.js mongodb driver async/await queries

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      相关资源
      最近更新 更多