我在快递中遇到问题。下面的一段代码找到pokemon集合中的所有值并逐个检查另一个集合以查找匹配。但是,在完成所有项目插入(display.insert(docs)
)之前,代码将达到res.send(documents)
。我知道这是因为节点异步工作的方式,但我找不到解决此问题的方法。我怎样才能确保所有的文件被插入?快递:如何在打电话前等待功能完成
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);
}
});
}
});
}
});
});
有这个问题的数百dups。您的一些操作是异步的。这意味着它们直到以后才会完成(仅在其回调中),但是您的代码假定它们是立即完成的,因此会在异步操作完成之前尝试完成。你无法做任何等待。相反,您必须通过在完成回调中继续进行处理来编写异步结果。 – jfriend00