Express:在调用某个函数之前如何等待函数完成

Express: How to wait for a function to complete before calling something

本文关键字:函数 何等待 等待 调用 Express      更新时间:2023-09-26

我在快递有一个问题。下面的代码找到pokemon集合中的所有值,并逐个检查另一个集合以找到匹配。然而,在所有条目插入完成之前,代码到达res.send(documents) (display.insert(docs))。我知道这是因为节点异步工作的方式,但我找不到解决这个问题的方法。我如何确保所有的文档都被插入?

pokeRouter.get('/sightings/:type([a-z]+)', function(req, res) {
display.deleteMany({}, function(err, bool) {
    if (err) throw err;
    if (bool) {
        pokemon.find().each(function(err, item) {
            if (err) throw err;
            if (item == null) {
                display.find().toArray(function(err, documents) {
                    if (err) throw err;
                    res.send(documents);
                })
            } else if ((req.params.type == item.type1) || (req.params.type == item.type2)) {
                sightings.find({
                    pokedex_id: item._id
                }).toArray(function(err, docs) {
                    if (docs == null) {
                        return null;
                    } else {
                        display.insert(docs);
                    }
                });
            }
        });
    }
});
});

您的display.insert(...)函数可能也是异步的。因此,find().each(...)内部的函数在插入完成之前返回。

我强烈建议将你的回调转换为承诺,或者使用async模块来处理你的异步内容

不使用Promises或async模块,你可以重构你的代码有文档变量外的异步代码和积累所有可插入的项目,在你的异步代码你会有某种类型的检查(如果一切都插入),然后我将调用res.send(documents)