究竟回调如何获得他们的论点? [英] How exactly callbacks get their arguments?

查看:51
本文介绍了究竟回调如何获得他们的论点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解JavaScript中的回调如何获得他们的参数。或者换句话说:如何实现更高阶的函数,使其回调接受例如标准的错误数据参数。

I have trouble understanding how callbacks in JavaScript get their arguments. Or in other words: how to implement a higher-order function so its callback accepts for instance a standard err and data arguments.

这篇关于异步JavaScript的文章在回调的例子中以通常的方式使用(我知道这是常见的,因为我看到了Node中使用的这种模式。 js moongose(即用于在db中创建数据)):

Like in this article on asynchronous JavaScript in the example of a callback used in a usual way (and I know it's usual because I see exactly this pattern used in Node.js moongose (i.e. for creating data in db)):

function getData(options, callback) { 
    $.get("example.php", options, function(response) { 
        callback(null, JSON.parse(response)); 
    }, function() { 
        callback(new Error("AJAX request failed!")); 
    }); 
} 

// usage 
getData({name: "John"}, function(err, data) { 
    if(err) { 
        console.log("Error! " + err.toString()) 
    } else { 
        console.log(data); 
    } 
});

回调获取参数的确切方式错误& ; data 基于 getData()函数如何在上面声明?

how exactly the callback gets arguments err & data based on how getData() function is declared above?

推荐答案

调用该函数时,会将参数传递给函数。

Arguments are passed to a function when that function is called.

function foo(arg) {
    console.log(arg);
}

foo("This is the value");

当它是回调函数时仍然如此。

This is still true when it is a callback function.

function foo(arg) {
    console.log(arg);
}

function bar(callback) {
    callback("This is the value");
}

bar(foo);

当回调函数由其他人编写的代码调用时,它仍然是正确的,该代码存在于库中,而您没有检查源代码。

And it is still true when the callback function is called by code written by someone else that exists in a library you aren't examining the source code of.

这篇关于究竟回调如何获得他们的论点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆