【发布时间】:2022-11-20 17:16:24
【问题描述】:
I build a scraper where the scraped data gets compared with already existing data to avoid duplicates, create new entries and update old entries. I'm doing this with a for loop, which loops over a findOne function where are two awaits in. The problem is that my for loop is ignoring (because it's sync?) my awaits and goes over to a part, where it is important that all of these awaits are done.
async function comparedata(length) {
console.log("Starting comparing entries in data");
for (let x = 0; x < length; x++) {
const model = new dataModel({
link: dataLinks[x],
name: dataGames[x].replace('Download', ' '),
logo: dataLogos[x],
provider: 'data',
});
model.collection.findOne({ "link": dataLinks[x] }, async function (err, found) {
if (err) throw err;
if (found == null) {
await model.save().then((result) => {
console.log(result) // Is not happening because the for loop goes through to the next function and closes the server
}).catch((err) => { console.log(err) });
}
else if (found != null) {
if (dataGames[x] != found.name) {
await model.collection.findOneAndUpdate({ link: dataLinks[x] }, { $set: { name: dataGames[x] } });
}
}
})
}
closeServer()//Closes the server is happening before new entries or updates are made.
}
我的想法是使用 promises,但即使我尝试这样做,它也只是解决得太快并再次关闭服务器。
【问题讨论】:
-
因为你使用的是
findOne的回调版本 -
是的,因为我需要比较单个条目
-
是的,但是
findOne的回调版本不支持 promise。即使您进行了回调async,它也只会在循环结束后执行。这也是findOne的承诺版本,您可以像let found = await model.collection.findOne(...)一样调用它 -
if (x > length) sendErrorMail();是什么意思?这永远不会发生,因为你的 for 循环的条件是x < length并且你在循环体内既没有修改x也没有修改length... -
x > length 来自以前的版本,因为函数参数名为 length。需要删除,抱歉。
标签: javascript node.js asynchronous mongoose async-await