此回调的结构是否正确

is this callback structured correctly?

本文关键字:是否 结构 回调      更新时间:2023-09-26

我想保存所有部分,使用刚刚保存的部分的ID更新问题,然后保存问题,然后如果成功触发重定向页面的函数nextPage。我正在尝试确认这是正确的。如果我没有围绕 saveAllQuestions 的匿名功能,这似乎很有趣。

saveAllSections(function () {saveAllQuestions(nextPage)});

更新:

关于saveAllSection的成功,它执行以下操作:

if (typeof(callback) == 'function')
               callback(); 

关于 saveAllQuestions 的成功,它执行以下操作:

            if (questionValuesToSave.length>0) {
                saveAllQuestionValues(questionValuesToSave, callback);
            }
            else {
                 // once its done hide AJAX saving modal
                hideModal();
                if (typeof(callback) == 'function')
                    callback();
            } 

关于saveAllQuestionValues的成功(假设有一些(,它执行以下操作:

                    if (typeof(callback) == 'function')
                        callback();
是的,这是回

调的一般正确语法,尽管如果不看到更多代码,很难确定。

以下代码

saveAllSections(saveAllQuestions(nextPage));

会失败,因为saveAllQuestions(nextPage)是执行函数的语法,而不是定义函数。 因此,它将立即执行并将结果传递给saveAllSections,这将尝试将其用作回调。 由于这可能不是一个函数,而且几乎肯定不是你想要传递的函数,你会得到奇怪的行为,很可能是一个错误。

将其包装在匿名函数中意味着您将一个函数传递给 saveAllSections ,该函数在被外部函数调用或作为回调之前不会执行。

更新:

看起来 saveAllQuestions 根据您的描述也是异步的,因此立即执行它肯定无法正常工作。 如果需要传递参数,匿名函数包装器是完全可以接受的解决方案。

如果你没有,你可以使用

saveAllSections(saveAllQuestions)
您需要将

saveAllQuestions包装在匿名函数中的原因是,否则saveAllQuestions会立即执行,并且其返回值将作为回调传递给saveAllSections

如果将saveAllQuestions包装在匿名函数中,则会阻止saveAllQuestions立即执行。

在javascript中,你可以将函数作为参数传递。 这允许更简单的代码和异步回调。 在您的尝试中,您不会传入函数。 您执行一个函数,因此saveAllQuestions(nextPage)的结果将传递到函数中,而不是函数saveAllQuestions

希望这个例子有所帮助。

function add(a,b) {
    return a+b;
}
function mul(a,b) {
    return a*b;
}
function doMath(num1, num2, op) {
    return op(num1, num2);
}
document.write( doMath(4,5, add) ); // 9
document.write( doMath(4,5, function (n1,n2) {return n1+n2;}) ); // 9
document.write( doMath(2,5, mul) ); // 10
document.write( doMath(2,5, function (n1,n2) {return n1*n2;}) ); // 10
document.write( doMath( doMath(1,3, add) , 4, mul) ); // 16