gpt4 book ai didi

javascript - 我的回调有什么问题?

转载 作者:行者123 更新时间:2023-11-30 08:35:35 24 4
gpt4 key购买 nike

我正在尝试学习回调并想知道我在这里做错了什么,因为我希望在 4 秒后收到一条消息:

I've tried to fire but one of the funcs isn't finished yet

8 秒后紧接着是另一条消息:

I waited for the two functions to finish and now I've fired

相反,我只是得到:

I waited for the two functions to finish and now I've fired

两次,分别在 4 秒后和 8 秒后。

var cbvarone = false;
var cbvartwo = false;

var whenOthersFinished = function() {
if (cbvartwo && cbvartwo) {
console.log("I waited for the two functions to finish and now I've fired");
}
else {
console.log("I've tried to fire but one of the funcs isn't finished yet");
}
};

var firstFunc = function(cb) {
setTimeout(function(){cbvarone = true; cb();}, 8000);
};

var secondFunc = function(cb) {
setTimeout(function(){cbvartwo = true; cb();}, 4000);
};

firstFunc(whenOthersFinished);
secondFunc(whenOthersFinished);

最佳答案

在你的函数中:

var whenOthersFinished = function() {
if (cbvartwo && cbvartwo) {
console.log("I waited for the two functions to finish and now I've fired");
}
else {
console.log("I've tried to fire but one of the funcs isn't finished yet");
}
};

你的 if 语句是:

if (cbvartwo && cbvartwo)

将其更改为:

if (cbvarone && cbvartwo)

一切都应该没问题。我已验证并且您的代码在更改后按预期工作

关于javascript - 我的回调有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31617557/

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