我正在尝试学习回调并想知道我在这里做错了什么,因为我希望在 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/