我在Express中遇到了问题。下面的代码找到了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);
}
});
}
});
}
});
});
答案 0 :(得分:2)
您的display.insert(...)
功能可能也是异步的。因此find().each(...)
内的函数在插入完成之前返回。
我强烈建议您将回调转换为Promises或使用异步模块来处理异步内容。
答案 1 :(得分:0)
不使用Promises或async模块,你可以重构你的代码,让文档在异步代码之外变量并累积所有可插入的项目,在你的异步代码中你会有一些类型的检查(如果插入了所有内容)那么我会打电话给res.send(文件)