gpt4 book ai didi

javascript - 虽然函数陷入循环,但循环的一半似乎没有执行

转载 作者:行者123 更新时间:2023-12-03 02:44:00 24 4
gpt4 key购买 nike

今天,我正在为一个有关流动民主的项目使用循环函数。在委托(delegate)投票时,我有一个 while 循环来检查是否忘记了任何委托(delegate),该算法有一个有趣的行为:

Vote.count({
propId: propId,
delegation: true
}, function(err, voteNumber) {
var maxDelegation = voteNumber;
for (var d = 1; d < maxDelegation + 1; d++) {
var delegationsLeft = 1; //Is calculated to see if someone delegates to a delegate
while (delegationsLeft > 0) {
console.log("I am about to find the votes for " + d + " weight, " + delegationsLeft + " delegation left at least.");
Vote.find({
propId: propId,
delegation: true,
weight: d
}, function(err, specWeightVotes) {
console.log("I'm in.");
delegationsLeft = specWeightVotes.length;
for (var i = 0; i < specWeightVotes.length; i++) {
// Add the weight d, aka the weight of a vote to the delegated voter
Vote.findOneAndUpdate({
propId: propId,
voter: specWeightVotes[i].content
}, {
$inc: {
'weight': specWeightVotes[i].weight
}
}, function(err) {
if (err) {
console.log("Ca bug.");
}

//Put weight as zero for the ones who have delegated
Vote.findOneAndUpdate({
_id: specWeightVotes[i]._id
}, {
$set: {
'weight': 0
}
}, function(err) {
if (err) {
console.log("Ca bug 2.");
}
});

});

}
});

}
}
console.log("I have delegated all votes");
});

现在有趣的是,我的 while 循环永远卡住了,因为它永远无法执行 Vote.find({propId: propId, delegate: true, Weight: d}, function(err, specWeightVotes) { 部分代码。

如果我查看控制台,我会得到以下输出:

I am about to find the votes for 1 weight, 1 delegation left at least.
I am about to find the votes for 1 weight, 1 delegation left at least.
I am about to find the votes for 1 weight, 1 delegation left at least.
I am about to find the votes for 1 weight, 1 delegation left at least.
I am about to find the votes for 1 weight, 1 delegation left at least.

...直到最终进程耗尽电池。我从来没有看到“我在”的部分。

我想这可以通过更多的异步编程来解决?但是,考虑到我的函数甚至不执行一次,我不确定。

PS:重要提示,在包含此 while 循环以防止忘记委托(delegate)之前,算法是有效的。

最佳答案

大概Vote.find异步地完成工作(对于Vote.findOneAndUpdate也类似)。您的 forwhile 循环不会。因此,在循环过程中,delegationsLeft 永远不会是 1。

如果您与异步结果交互,则不能使用 while(或 fordo-while)。相反,您需要从异步回调中安排“循环”的下一个“迭代”。

(或者将所有代码放入 ES2017+ async 函数中,将 Vote.find 等包装在返回 Promises 的包装器中,并使用 await。但这需要一个尖端的 JavaScript 环境来运行,或者使用 Babel 之类的东西进行转译。)

关于javascript - 虽然函数陷入循环,但循环的一半似乎没有执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com