有人可以在这里解释这个概念。我在代码中放了三个console.log,以了解这段代码是如何运行的。但是,我不明白为什么在 contestCount++ 移动到客户端 2 之前被调用了四次。(顺便说一下,竞赛集合中有四个文档)我希望代码从上到下一直循环然后循环再次回到顶部。谢谢
MongoClient.connect(
config.mongodbUri,
{ useUnifiedTopology: true },
(err, client) => {
assert.equal(null, err);
let contestCount = 0;
/* client 1 */
client
.db('test')
.collection('contests')
.find({})
.each((err, contest) => {
assert.equal(null, err);
if (!contest) {
return;
}
contestCount++;
/* console.log */
console.log(`contestCountPlus: ${contestCount}`);
/* client 2 */
client
.db('test')
.collection('names')
.find({ id: { $in: contest.nameIds } })
.project({ _id: 1 })
.toArray()
.then((_ids) => {
const newIds = _ids.map((o) => o._id);
/* client 3 */
client
.db('test')
.collection('contests')
.updateOne({ id: contest.id }, { $set: { nameIds: newIds } })
.then(() => {
contestCount--;
/* console.log */
console.log(`contestCountMinus: ${contestCount}`);
if (contestCount === 0) {
/* console.log */
console.log(`contestCountFinal: ${contestCount}`);
client.close();
}
});
})
.catch(console.error);
});
}
);
这是我从终端得到的
Stevens-MBP:learn-fullstack-javascript stevenlai$ babel-node updateTestData.js
contestCountPlus: 1
contestCountPlus: 2
contestCountPlus: 3
contestCountPlus: 4
contestCountMinus: 3
contestCountMinus: 2
contestCountMinus: 1
contestCountMinus: 0
contestCountFinal: 0