我的回调有什么问题?

What's wrong with my Callback?

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

你有:

if (cbvartwo && cbvartwo) {

我想你的意思是:

if (cbvarone && cbvartwo) {

if (cbvartwo && cbvartwo) {

应该是

if (cbvarone && cbvartwo) {

在你的函数中:

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)

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