简体   繁体   English

您能向我解释这个Javascript回调函数吗?

[英]Can you explain this Javascript callback function to me?

If I have the following callback function: 如果我有以下回调函数:

a(function  () {
  b() 
})

my understanding is that a would be executed first, then b once a is finished 我的理解是,将首先执行a,然后在完成a之后执行b

But generally in programming, you pass parameters to a function within the parantheses right? 但是通常在编程中,您可以在括号内将参数传递给函数,对吗? So in this function, it seems as though you are passing 因此,在此函数中,好像您正在传递

function  () {
  b() 
}

to the function a as an argument. 函数a作为参数。 So according to what I know about programming, a should execute with all of that as an argument right? 因此,根据我对编程的了解,a应该以所有参数作为参数执行对吗?

Yet according to what I know about callbacks, it means instead, that all of that executes after the a function executes. 但是,根据我对回调的了解,它意味着所有这些都在函数执行之后执行。 Can you see the contradiction? 你看到矛盾了吗? Also, then wouldn't the function a be executing without parameters? 另外,函数不具有参数就不会执行吗?

Do parameters just work differently in javascript. 参数在javascript中的作用不同吗? By default, does all the stuff in the parentheses execute after the function itself? 默认情况下,括号中的所有内容是否在函数本身之后执行?

The a() function would have to have an argument that is actually a callback, it doesn't just work automagically a()函数必须有一个实际上是回调的参数,它不能自动地工作

function a(callback) {  // callback argument
    // do lots of stuff

    callback(); // call the function after stuff has been done
}

a(function() {
    b();
});

And you could also just do 你也可以做

a(b);

and pass arguments to the callback 并将参数传递给回调

function a(callback) {  // callback argument
    // do lots of stuff

    callback(param1, param2, param3);
}

a(function(param1, param2, param3) { // here we get them back
    b(param2); // and we can pass them along
});

This is especially useful with async behaviour 这对于异步行为特别有用

function a(callback) {  // callback argument

    $.ajax({
        // ajax arguments
    }).done(function(returned_data) {

        callback(returned_data);

    });

}

a(function(returned_data) { // data from the ajax call
     // do something with returned_data
});

That's just an example, $.ajax returns a promise that is more handy to use, but it shows how a callback would work with async functions. 这只是一个示例,$。ajax返回一个更易于使用的promise,但是它显示了回调如何与异步函数一起工作。

As a sidenote, you'll often see code where a callback is not guaranteed, and then it makes sense to check if there was a callback function passed as an argument before trying to execute it to avoid errors. 附带说明,您经常会在代码中看到无法保证回调的情况,然后在尝试执行回调函数以避免错误之前检查是否有作为参数传递的回调函数才有意义。

function a(callback) {  // callback argument
    // do lots of stuff

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM