我在快遞中遇到問題。下面的一段代碼找到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